All files / src/views CodeReviewPanel.js

100% Statements 970/970
100% Branches 137/137
100% Functions 24/24
100% Lines 970/970

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 97125x 25x 25x 25x 25x 25x 25x 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 25x 25x 25x 25x 25x 8x 8x 8x 1x 1x 7x 7x 7x 2x 7x 5x 5x 5x 5x 5x 5x 5x 5x 4x 5x 2x 2x 5x 5x 5x 7x 7x 7x 7x 7x 7x 7x 7x 8x 5x 5x 5x 5x 5x 5x 5x 8x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 8x 5x 8x 1x 1x 8x 1x 1x 1x 8x 25x 25x 25x 25x 25x 2x 2x 2x 2x 2x 2x 2x 2x 2x 25x 25x 25x 25x 25x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 25x 25x 25x 25x 25x 7x 6x 6x 6x 6x 6x 6x 7x 25x 25x 25x 25x 25x 4x 4x 4x 4x 128x 128x 4x 4x 25x 25x 25x 25x 25x 1x 1x 1x 1x 25x 25x 25x 25x 25x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 25x 25x 25x  
/**
 * Code Review Panel - Webview en Source Control View Container
 * Muestra resultados de code review en una interfaz visual
 */
 
const vscode = require("vscode");
const path = require("path");
 
class CodeReviewPanel {
  static viewType = "gbot.codeReviewPanel";
 
  constructor(extensionUri) {
    this._extensionUri = extensionUri;
    this._view = undefined;
    this._commentController = undefined;
    this._allComments = [];
    this._currentCommentIndex = -1;
    this._commentThreads = [];
    this._statusBarItem = undefined;
    this._currentBaseBranch = "";
    this._currentTargetBranch = "";
    this._disposables = []; // Array para event listeners y recursos
 
    // Crear status bar item
    this._statusBarItem = vscode.window.createStatusBarItem(
      vscode.StatusBarAlignment.Right,
      100,
    );
    this._disposables.push(this._statusBarItem);
  }
 
  /**
   * Implementa WebviewViewProvider
   */
  resolveWebviewView(webviewView, context, token) {
    this._view = webviewView;
 
    webviewView.webview.options = {
      enableScripts: true,
      localResourceRoots: [
        this._extensionUri,
        vscode.Uri.joinPath(this._extensionUri, "media"),
      ],
    };
 
    webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);
 
    // Escuchar mensajes del webview con disposable para evitar memory leaks
    const messageListener = webviewView.webview.onDidReceiveMessage(
      async (data) => {
        await this._handleWebviewMessage(data);
      },
    );
 
    // Agregar listener al array de disposables para limpieza posterior
    if (!this._disposables) {
      this._disposables = [];
    }
    this._disposables.push(messageListener);
 
    // Limpiar cuando la vista se oculte
    webviewView.onDidDispose(() => {
      this.dispose();
    });
  }
 
  /**
   * Maneja mensajes del webview
   */
  async _handleWebviewMessage(data) {
    switch (data.type) {
      case "openFile":
        await this._openFileWithComment(data.filePath, data.line, data.comment);
        break;
 
      case "nextComment":
        await this.navigateToNext();
        break;
 
      case "previousComment":
        await this.navigateToPrevious();
        break;
 
      case "applyFix":
        // Mostrar diálogo interactivo en lugar de aplicar directamente
        const suggestion = {
          originalCode: data.originalCode,
          adjustedCode: data.adjustedCode,
          description: "Fix sugerido",
        };
        const commentData = {
          message: data.message || "Aplicar sugerencia",
          severity: data.severity || "info",
          suggestion: suggestion,
          line: data.startLine || 1,
        };
        await this._showFixOptionsDialog(commentData, data.filePath);
        break;
 
      case "clearComments":
        await this._clearAllComments();
        break;
 
      case "reviewUncommitted":
        await vscode.commands.executeCommand(
          "gbot.reviewUnstagedChanges",
        );
        break;
 
      case "reviewBranch":
        await vscode.commands.executeCommand("gbot.compareBranches");
        break;
 
      case "evaluateRisk":
        await vscode.commands.executeCommand("gbot.analyzeRisk");
        break;
 
      case "reviewWithStandards":
        await vscode.commands.executeCommand("gbot.reviewStagedChanges");
        break;
    }
  }
 
  /**
   * Muestra resultados del code review
   */
  async displayReviewResults(results) {
    if (!this._view) {
      return;
    }
 
    try {
      // Limpiar comentarios anteriores
      await this._clearAllComments();
 
      // Procesar resultados y extraer comentarios
      this._allComments = [];
 
      if (results.files && Array.isArray(results.files)) {
        for (const file of results.files) {
          if (file.issues && Array.isArray(file.issues)) {
            for (const issue of file.issues) {
              this._allComments.push({
                filePath: file.path,
                line: issue.line || 1,
                severity: issue.severity || "info",
                message:
                  issue.message ||
                  issue.comment ||
                  issue.description ||
                  "Sin mensaje",
                suggestion:
                  issue.suggestion ||
                  issue.proposedAdjustment ||
                  issue.recommendation,
              });
            }
          }
        }
      } else {
        // No files array in results - skip
      }
 
      // Enviar resultados al webview
      this._view.webview.postMessage({
        type: "reviewCompleted",
        results: results,
      });
 
      // Ocultar status bar si no hay comentarios
      if (this._allComments.length === 0) {
        if (this._statusBarItem) {
          this._statusBarItem.hide();
        }
      } else {
        // Actualizar status bar
        this._updateStatusBar();
      }
    } catch (error) {
      console.error("Error displaying results:", error);
      this._view.webview.postMessage({
        type: "reviewError",
        message: error.message || "Error desconocido",
      });
    }
  }
 
  /**
   * Muestra progreso del review
   */
  showProgress(message) {
    if (this._view) {
      this._view.webview.postMessage({
        type: "reviewProgress",
        message: message,
      });
    }
  }
 
  /**
   * Muestra que el review comenzó
   */
  showReviewStarted() {
    if (this._view) {
      this._view.webview.postMessage({
        type: "reviewStarted",
      });
    }
  }
 
  /**
   * Abre archivo con comentario y crea thread
   */
  async _openFileWithComment(filePath, line, comment) {
    try {
      // Encontrar índice del comentario - buscar por archivo y línea primero
      this._currentCommentIndex = this._allComments.findIndex(
        (c) => c.filePath === filePath && c.line === line,
      );
 
      // Si no se encuentra, buscar solo por línea (puede que la ruta sea diferente)
      if (this._currentCommentIndex === -1) {
        this._currentCommentIndex = this._allComments.findIndex(
          (c) => c.line === line,
        );
      }
 
      // Si aún no se encuentra, tomar el primer comentario
      if (this._currentCommentIndex === -1) {
        this._currentCommentIndex = 0;
      }
      await this._showCommentAtIndex(this._currentCommentIndex);
    } catch (error) {
      console.error("Error opening file with comment:", error);
      vscode.window.showErrorMessage(
        `Error al abrir archivo: ${error.message}`,
      );
    }
  }
 
  /**
   * Muestra comentario en el índice especificado
   */
  async _showCommentAtIndex(index) {
    if (index < 0 || index >= this._allComments.length) {
      return;
    }
 
    const commentData = this._allComments[index];
 
    try {
      // Limpiar threads anteriores
      this._commentThreads.forEach((thread) => thread.dispose());
      this._commentThreads = [];
 
      // Construir ruta absoluta
      const workspaceFolders = vscode.workspace.workspaceFolders;
      if (!workspaceFolders || workspaceFolders.length === 0) {
        throw new Error("No workspace folder open");
      }
 
      let absolutePath;
      if (path.isAbsolute(commentData.filePath)) {
        absolutePath = commentData.filePath;
      } else {
        // Verificar si el path relativo ya incluye el workspace name
        const workspaceRoot = workspaceFolders[0].uri.fsPath;
        const workspaceName = path.basename(workspaceRoot);
 
        // Si el filePath comienza con el workspace name, quitarlo
        let cleanPath = commentData.filePath;
        if (
          cleanPath.startsWith(workspaceName + path.sep) ||
          cleanPath.startsWith(workspaceName + "/")
        ) {
          cleanPath = cleanPath.substring(workspaceName.length + 1);
        }
 
        absolutePath = path.join(workspaceRoot, cleanPath);
      }
 
      // Abrir el archivo
      const uri = vscode.Uri.file(absolutePath);
      const document = await vscode.workspace.openTextDocument(uri);
      const editor = await vscode.window.showTextDocument(document);
 
      // Navegar a la línea
      const line = Math.max(0, commentData.line - 1);
      const position = new vscode.Position(line, 0);
      editor.selection = new vscode.Selection(position, position);
      editor.revealRange(
        new vscode.Range(position, position),
        vscode.TextEditorRevealType.InCenter,
      );
 
      // Crear comment controller si no existe
      if (!this._commentController) {
        this._commentController = vscode.comments.createCommentController(
          "G-Bot-code-review",
          "G-Bot Code Review",
        );
        this._commentController.commentingRangeProvider = {
          provideCommentingRanges: () => [],
        };
      }
 
      // Crear comment thread
      const range = new vscode.Range(position, position);
      const thread = this._commentController.createCommentThread(
        uri,
        range,
        [],
      );
 
      // Crear contenido del comentario
      const currentNum = index + 1;
      const totalNum = this._allComments.length;
 
      const severityIcon = this._getSeverityIcon(commentData.severity);
      const markdownBody = new vscode.MarkdownString();
 
      markdownBody.appendMarkdown(
        `${severityIcon} **Code Review (${currentNum}/${totalNum})**\n\n`,
      );
      markdownBody.appendMarkdown(`${commentData.message}\n\n`);
 
      // Agregar sugerencia si existe
      if (commentData.suggestion) {
        markdownBody.appendMarkdown("---\n\n");
        markdownBody.appendMarkdown("**💡 Sugerencia:**\n\n");
 
        if (typeof commentData.suggestion === "string") {
          markdownBody.appendMarkdown(`${commentData.suggestion}\n\n`);
        } else if (commentData.suggestion.description) {
          markdownBody.appendMarkdown(
            `${commentData.suggestion.description}\n\n`,
          );
 
          if (
            commentData.suggestion.originalCode &&
            commentData.suggestion.adjustedCode
          ) {
            markdownBody.appendMarkdown("**Original:**\n");
            markdownBody.appendCodeblock(
              commentData.suggestion.originalCode,
              "javascript",
            );
            markdownBody.appendMarkdown("\n**Sugerido:**\n");
            markdownBody.appendCodeblock(
              commentData.suggestion.adjustedCode,
              "javascript",
            );
          }
        }
      }
 
      markdownBody.isTrusted = true;
 
      // Crear comentario
      const comment = {
        body: markdownBody,
        mode: vscode.CommentMode.Preview,
        author: {
          name: "G-Bot Code Review",
          iconPath: vscode.Uri.joinPath(
            this._extensionUri,
            "resources",
            "icon.png",
          ),
        },
      };
 
      thread.comments = [comment];
      thread.canReply = false;
      thread.collapsibleState = vscode.CommentThreadCollapsibleState.Expanded;
 
      // Agregar context value para habilitar comandos
      thread.contextValue = "G-Bot-issue";
 
      // Si hay sugerencia, mostrar Quick Pick automáticamente
      if (commentData.suggestion && commentData.suggestion.description) {
        // Pequeño delay para que el thread se renderice primero
        setTimeout(async () => {
          await this._showFixOptionsDialog(commentData, absolutePath);
        }, 500);
      }
 
      this._commentThreads.push(thread);
 
      // Actualizar status bar
      this._updateStatusBar();
    } catch (error) {
      console.error("Error showing comment:", error);
      vscode.window.showErrorMessage(
        `Error al mostrar comentario: ${error.message}`,
      );
    }
  }
 
  /**
   * Obtiene icono según severidad
   */
  _getSeverityIcon(severity) {
    const icons = {
      error: "🔴",
      warning: "⚠️",
      info: "ℹ️",
      suggestion: "💡",
      critical: "🚨",
      high: "🔴",
      medium: "⚠️",
      low: "ℹ️",
    };
    return icons[severity?.toLowerCase()] || "ℹ️";
  }
 
  /**
   * Actualiza status bar
   */
  _updateStatusBar() {
    if (!this._statusBarItem) return;
 
    if (this._allComments.length === 0) {
      this._statusBarItem.hide();
      return;
    }
 
    const currentNum = this._currentCommentIndex + 1;
    const totalNum = this._allComments.length;
 
    this._statusBarItem.text = `$(comment) Review: ${currentNum}/${totalNum}`;
    this._statusBarItem.tooltip = `Comentario ${currentNum} de ${totalNum}`;
    this._statusBarItem.command = "gbot.nextComment";
    this._statusBarItem.show();
  }
 
  /**
   * Muestra diálogo interactivo para aplicar o rechazar un fix
   */
  async _showFixOptionsDialog(commentData, filePath) {
    const suggestion = commentData.suggestion;
    if (!suggestion) return;
 
    const severityIcon = this._getSeverityIcon(commentData.severity);
 
    // Verificar si hay código aplicable
    const hasApplicableCode =
      suggestion.originalCode &&
      suggestion.adjustedCode &&
      suggestion.originalCode !== suggestion.adjustedCode;
 
    // Crear opciones del Quick Pick según lo que tengamos
    const options = [];
 
    if (hasApplicableCode) {
      options.push({
        label: "$(check) Aplicar Fix",
        description: "Reemplazar el código con la sugerencia",
        action: "apply",
        iconPath: new vscode.ThemeIcon("check"),
      });
      options.push({
        label: "$(eye) Ver Diff",
        description: "Comparar código original vs sugerido",
        action: "diff",
      });
    } else {
      // Solo recomendación textual
      options.push({
        label: "$(info) Ver Recomendación",
        description: "Revisar la recomendación completa",
        action: "info",
      });
    }
 
    options.push({
      label: "$(close) Cerrar",
      description: "Cerrar este diálogo",
      action: "dismiss",
    });
 
    // Mostrar Quick Pick
    const selected = await vscode.window.showQuickPick(options, {
      placeHolder: `${severityIcon} ${commentData.message.substring(0, 80)}...`,
      title: "💡 Aplicar Sugerencia de Code Review",
      matchOnDescription: true,
    });
 
    if (!selected) return;
 
    switch (selected.action) {
      case "apply":
        await this._applyFixWithConfirmation(
          filePath,
          suggestion,
          commentData.line,
        );
        break;
 
      case "diff":
        await this._showDiffPreview(filePath, suggestion, commentData.line);
        break;
 
      case "info":
        // Mostrar recomendación completa en un panel de información
        const panel = vscode.window.createWebviewPanel(
          "codeReviewRecommendation",
          `💡 Recomendación - ${commentData.severity}`,
          vscode.ViewColumn.Beside,
          { enableScripts: false },
        );
 
        panel.webview.html = `
          <!DOCTYPE html>
          <html>
            <head>
              <meta charset="UTF-8">
              <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline';">
              <style>
                body {
                  font-family: var(--vscode-font-family);
                  padding: 20px;
                  color: var(--vscode-foreground);
                  background: var(--vscode-editor-background);
                }
                .header {
                  display: flex;
                  align-items: center;
                  gap: 10px;
                  margin-bottom: 20px;
                  padding-bottom: 15px;
                  border-bottom: 1px solid var(--vscode-panel-border);
                }
                .severity {
                  font-size: 24px;
                }
                .title {
                  font-size: 16px;
                  font-weight: bold;
                }
                .recommendation {
                  line-height: 1.6;
                  white-space: pre-wrap;
                  background: var(--vscode-textBlockQuote-background);
                  padding: 15px;
                  border-left: 3px solid var(--vscode-textBlockQuote-border);
                  border-radius: 4px;
                }
                .location {
                  margin-top: 20px;
                  font-size: 12px;
                  color: var(--vscode-descriptionForeground);
                }
              </style>
            </head>
            <body>
              <div class="header">
                <span class="severity">${this._escapeHtml(severityIcon)}</span>
                <span class="title">${this._escapeHtml(commentData.message)}</span>
              </div>
              <div class="recommendation">${this._escapeHtml(suggestion.description)}</div>
              <div class="location">📍 ${this._escapeHtml(filePath)}:${this._escapeHtml(String(commentData.line))}</div>
            </body>
          </html>
        `;
        break;
 
      case "dismiss":
        vscode.window.showInformationMessage("Diálogo cerrado");
        break;
    }
  }
 
  /**
   * Aplica fix con confirmación adicional
   */
  async _applyFixWithConfirmation(filePath, suggestion, line) {
    const originalCode = suggestion.originalCode || "";
    const adjustedCode = suggestion.adjustedCode || "";
 
    if (!originalCode || !adjustedCode) {
      vscode.window.showWarningMessage("No hay código de reemplazo disponible");
      return;
    }
 
    // Mostrar confirmación final
    const confirm = await vscode.window.showWarningMessage(
      `¿Aplicar fix en línea ${line}?`,
      {
        modal: true,
        detail: `Original: ${originalCode.substring(
          0,
          50,
        )}...\n\nSugerido: ${adjustedCode.substring(0, 50)}...`,
      },
      "Sí, Aplicar",
      "Cancelar",
    );
 
    if (confirm === "Sí, Aplicar") {
      await this._applyFix(filePath, originalCode, adjustedCode, line, line);
    }
  }
 
  /**
   * Muestra vista previa del diff en un editor temporal
   */
  async _showDiffPreview(filePath, suggestion, line) {
    try {
      const originalCode = suggestion.originalCode || "";
      const adjustedCode = suggestion.adjustedCode || "";
 
      if (!originalCode || !adjustedCode) {
        vscode.window.showWarningMessage("No hay código para comparar");
        return;
      }
 
      // Crear documentos temporales
      const originalDoc = await vscode.workspace.openTextDocument({
        content: originalCode,
        language: "javascript",
      });
 
      const suggestedDoc = await vscode.workspace.openTextDocument({
        content: adjustedCode,
        language: "javascript",
      });
 
      // Abrir diff
      await vscode.commands.executeCommand(
        "vscode.diff",
        originalDoc.uri,
        suggestedDoc.uri,
        `💡 Sugerencia (Línea ${line}) - Original ↔ Sugerido`,
      );
 
      // Preguntar si quiere aplicar después de ver el diff
      setTimeout(async () => {
        const apply = await vscode.window.showInformationMessage(
          "¿Aplicar este fix?",
          "Aplicar",
          "No",
        );
 
        if (apply === "Aplicar") {
          await this._applyFix(
            filePath,
            originalCode,
            adjustedCode,
            line,
            line,
          );
        }
      }, 1000);
    } catch (error) {
      console.error("Error showing diff:", error);
      vscode.window.showErrorMessage(`Error al mostrar diff: ${error.message}`);
    }
  }
 
  /**
   * Navega al siguiente comentario
   */
  async navigateToNext() {
    if (this._allComments.length === 0) {
      vscode.window.showInformationMessage("No hay comentarios disponibles");
      return;
    }
 
    this._currentCommentIndex =
      (this._currentCommentIndex + 1) % this._allComments.length;
    await this._showCommentAtIndex(this._currentCommentIndex);
  }
 
  /**
   * Navega al comentario anterior
   */
  async navigateToPrevious() {
    if (this._allComments.length === 0) {
      vscode.window.showInformationMessage("No hay comentarios disponibles");
      return;
    }
 
    this._currentCommentIndex =
      this._currentCommentIndex <= 0
        ? this._allComments.length - 1
        : this._currentCommentIndex - 1;
 
    await this._showCommentAtIndex(this._currentCommentIndex);
  }
 
  /**
   * Aplica un fix sugerido
   */
  async _applyFix(filePath, originalCode, adjustedCode, startLine, endLine) {
    try {
      const workspaceFolders = vscode.workspace.workspaceFolders;
      if (!workspaceFolders || workspaceFolders.length === 0) {
        throw new Error("No workspace folder open");
      }
 
      let absolutePath;
      if (path.isAbsolute(filePath)) {
        absolutePath = filePath;
      } else {
        // Verificar si el path relativo ya incluye el workspace name
        const workspaceRoot = workspaceFolders[0].uri.fsPath;
        const workspaceName = path.basename(workspaceRoot);
 
        // Si el filePath comienza con el workspace name, quitarlo
        let cleanPath = filePath;
        if (
          cleanPath.startsWith(workspaceName + path.sep) ||
          cleanPath.startsWith(workspaceName + "/")
        ) {
          cleanPath = cleanPath.substring(workspaceName.length + 1);
        }
 
        absolutePath = path.join(workspaceRoot, cleanPath);
      }
 
      const uri = vscode.Uri.file(absolutePath);
      const document = await vscode.workspace.openTextDocument(uri);
      const editor = await vscode.window.showTextDocument(document);
 
      let range;
 
      // Usar líneas si están disponibles
      if (startLine !== undefined && endLine !== undefined) {
        const start = new vscode.Position(Math.max(0, startLine - 1), 0);
        const endLineIndex = Math.min(endLine - 1, document.lineCount - 1);
        const end = new vscode.Position(
          endLineIndex,
          document.lineAt(endLineIndex).text.length,
        );
        range = new vscode.Range(start, end);
      } else {
        // Buscar el código original
        const text = document.getText();
        const index = text.indexOf(originalCode);
 
        if (index === -1) {
          vscode.window.showWarningMessage(
            "No se pudo encontrar el código original. El archivo puede haber cambiado.",
          );
          return;
        }
 
        const startPos = document.positionAt(index);
        const endPos = document.positionAt(index + originalCode.length);
        range = new vscode.Range(startPos, endPos);
      }
 
      // Aplicar el edit
      const success = await editor.edit((editBuilder) => {
        editBuilder.replace(range, adjustedCode);
      });
 
      if (success) {
        vscode.window.showInformationMessage("✅ Fix aplicado exitosamente");
      } else {
        vscode.window.showErrorMessage("❌ Error al aplicar el fix");
      }
    } catch (error) {
      console.error("Error applying fix:", error);
      vscode.window.showErrorMessage(`Error: ${error.message}`);
    }
  }
 
  /**
   * Limpia todos los comentarios
   */
  async _clearAllComments() {
    this._commentThreads.forEach((thread) => thread.dispose());
    this._commentThreads = [];
    this._allComments = [];
    this._currentCommentIndex = -1;
 
    if (this._statusBarItem) {
      this._statusBarItem.hide();
    }
  }
 
  /**
   * Obtiene HTML para el webview
   */
  _getHtmlForWebview(webview) {
    const scriptUri = webview.asWebviewUri(
      vscode.Uri.joinPath(this._extensionUri, "media", "main.js"),
    );
    const styleResetUri = webview.asWebviewUri(
      vscode.Uri.joinPath(this._extensionUri, "media", "reset.css"),
    );
    const styleVSCodeUri = webview.asWebviewUri(
      vscode.Uri.joinPath(this._extensionUri, "media", "vscode.css"),
    );
    const styleMainUri = webview.asWebviewUri(
      vscode.Uri.joinPath(this._extensionUri, "media", "main.css"),
    );
 
    const nonce = this._getNonce();
 
    return `<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource} 'unsafe-inline'; script-src 'nonce-${nonce}';">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="${styleResetUri}" rel="stylesheet">
    <link href="${styleVSCodeUri}" rel="stylesheet">
    <link href="${styleMainUri}" rel="stylesheet">
    <title>G-Bot Code Review</title>
    <style>
        /* Critical CSS to ensure dropdown is hidden by default */
        .dropdown-menu {
            display: none !important;
            position: absolute;
            top: calc(100% + 4px);
            right: 0;
            background: var(--vscode-menu-background);
            border: 1px solid var(--vscode-menu-border);
            border-radius: 4px;
            min-width: 220px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            z-index: 1000;
        }
        .dropdown-menu.show {
            display: block !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-content">
                <h2>🔍 Code Review</h2>
            </div>
            <div class="toolbar">
                <div class="dropdown">
                    <button class="toolbar-button dropdown-toggle" id="btnActions" title="Acciones de Code Review">
                        <span class="icon">⚙️</span>
                        <span class="button-label">Acciones</span>
                    </button>
                    <div class="dropdown-menu" id="dropdownMenu">
                        <div class="dropdown-item" data-action="reviewUncommitted">
                            <span class="icon">📝</span>
                            <span>Revisar Cambios Uncommitted</span>
                        </div>
                        <div class="dropdown-item" data-action="reviewBranch">
                            <span class="icon">🌿</span>
                            <span>Comparar con Branch</span>
                        </div>
                        <div class="dropdown-item" data-action="evaluateRisk">
                            <span class="icon">🛡️</span>
                            <span>Evaluar Riesgo</span>
                        </div>
                        <div class="dropdown-item" data-action="reviewWithStandards">
                            <span class="icon">✅</span>
                            <span>Revisar con Estándares</span>
                        </div>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-item" data-action="nextComment">
                            <span class="icon">⬇️</span>
                            <span>Siguiente Comentario</span>
                        </div>
                        <div class="dropdown-item" data-action="previousComment">
                            <span class="icon">⬆️</span>
                            <span>Comentario Anterior</span>
                        </div>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-item" data-action="clearComments">
                            <span class="icon">🗑️</span>
                            <span>Limpiar Comentarios</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
 
        <div class="status-section" id="statusSection">
            <div id="statusMessage" class="status-idle">
                Listo para revisar código
            </div>
        </div>
 
        <div class="results-section" id="resultsSection">
            <div id="reviewResults"></div>
        </div>
    </div>
 
    <script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
  }
 
  /**
   * Escapa caracteres HTML para prevenir XSS
   */
  _escapeHtml(text) {
    if (!text || typeof text !== "string") return "";
    return text
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  }
 
  /**
   * Genera nonce para CSP
   */
  _getNonce() {
    let text = "";
    const possible =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (let i = 0; i < 32; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
  }
 
  /**
   * Refresca el panel
   */
  refresh() {
    if (this._view) {
      this._view.webview.html = this._getHtmlForWebview(this._view.webview);
    }
  }
 
  /**
   * Dispose
   */
  dispose() {
    // Limpiar todos los disposables (incluye event listeners)
    if (this._disposables) {
      this._disposables.forEach((d) => {
        try {
          d.dispose();
        } catch (error) {
          console.error("Error disposing resource:", error);
        }
      });
      this._disposables = [];
    }
 
    // Limpiar comment threads
    this._commentThreads.forEach((thread) => thread.dispose());
    this._commentThreads = [];
 
    // Limpiar comment controller
    if (this._commentController) {
      this._commentController.dispose();
      this._commentController = undefined;
    }
 
    // Limpiar status bar
    if (this._statusBarItem) {
      this._statusBarItem.dispose();
      this._statusBarItem = undefined;
    }
 
    // Limpiar referencias
    this._view = undefined;
    this._allComments = [];
    this._currentCommentIndex = -1;
  }
}
 
module.exports = CodeReviewPanel;