/**
 * Post-validation share trigger for VS Code extension.
 *
 * Renders the share section that appears immediately after
 * grade reveal in the webview report panel.
 */

export interface ShareOptions {
  grade: string;
  score: number;
  passedCount: number;
  totalCount: number;
  projectName: string;
}

/** Badge color mapping by letter grade. */
const GRADE_COLORS: Record<string, string> = {
  "A+": "10B981",
  A: "22C55E",
  "A-": "34D399",
  "B+": "6366F1",
  B: "818CF8",
  "B-": "A5B4FC",
  "C+": "F59E0B",
  C: "FBBF24",
  "C-": "FCD34D",
  D: "EF4444",
  F: "DC2626",
};

export class ShareTrigger {
  /**
   * Generate the share section HTML for the webview.
   */
  static getShareSectionHtml(options: ShareOptions): string {
    const { grade, score, projectName } = options;
    const badgeMarkdown = this.getBadgeMarkdown(grade, score, projectName);
    const shareUrl = `https://deepsweep.ai/badge/${encodeURIComponent(projectName)}`;
    const twitterUrl = this.getTwitterUrl(grade, score, shareUrl);
    const linkedinUrl = this.getLinkedInUrl(shareUrl);
    const escapedBadgeMarkdown = badgeMarkdown.replace(/'/g, "\\'");

    return `
      <section class="share-section mt-8 p-6 bg-gray-800 rounded-xl border border-gray-700">
        <h3 class="text-lg font-semibold text-white mb-2">Share Your Grade</h3>
        <p class="text-gray-400 text-sm mb-4">
          Add a security badge to your README or share your results
        </p>

        <!-- Badge Preview -->
        <div class="badge-preview mb-4 p-4 bg-gray-900 rounded-lg">
          <img
            src="${this.getBadgeUrl(grade, score)}"
            alt="DeepSweep Grade ${grade}"
            class="h-6"
          />
        </div>

        <!-- Action Buttons -->
        <div class="flex flex-wrap gap-3">
          <button
            onclick="copyBadge('${escapedBadgeMarkdown}')"
            class="px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-lg hover:bg-indigo-700 transition flex items-center gap-2"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
            </svg>
            Copy Badge for README
          </button>

          <a
            href="${twitterUrl}"
            target="_blank"
            class="px-4 py-2 bg-gray-700 text-white text-sm font-medium rounded-lg hover:bg-gray-600 transition flex items-center gap-2"
          >
            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
              <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"></path>
            </svg>
            Share on X
          </a>

          <a
            href="${linkedinUrl}"
            target="_blank"
            class="px-4 py-2 bg-gray-700 text-white text-sm font-medium rounded-lg hover:bg-gray-600 transition flex items-center gap-2"
          >
            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
              <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"></path>
            </svg>
            Share on LinkedIn
          </a>
        </div>

        <!-- Badge Markdown (hidden, for copy) -->
        <div id="badge-markdown" class="hidden">${badgeMarkdown}</div>
      </section>

      <script>
        function copyBadge(markdown) {
          navigator.clipboard.writeText(markdown).then(() => {
            const btn = event.target.closest('button');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg> Copied!';
            btn.classList.remove('bg-indigo-600', 'hover:bg-indigo-700');
            btn.classList.add('bg-green-600');
            setTimeout(() => {
              btn.innerHTML = originalText;
              btn.classList.remove('bg-green-600');
              btn.classList.add('bg-indigo-600', 'hover:bg-indigo-700');
            }, 2000);
          });

          // Track event via VS Code API
          if (typeof acquireVsCodeApi !== 'undefined') {
            const vscode = acquireVsCodeApi();
            vscode.postMessage({ command: 'trackShare', type: 'badge_copied' });
          }
        }
      </script>
    `;
  }

  static getBadgeUrl(grade: string, score: number): string {
    const color = GRADE_COLORS[grade] || "6366F1";
    const message = encodeURIComponent(`${grade} (${score})`);
    return `https://img.shields.io/badge/DeepSweep-${message}-${color}?style=flat-square`;
  }

  static getBadgeMarkdown(
    grade: string,
    score: number,
    projectName: string,
  ): string {
    const badgeUrl = this.getBadgeUrl(grade, score);
    const profileUrl = `https://deepsweep.ai/badge/${encodeURIComponent(projectName)}`;
    return `[![DeepSweep Security Grade](${badgeUrl})](${profileUrl})`;
  }

  static getTwitterUrl(
    grade: string,
    score: number,
    shareUrl: string,
  ): string {
    const text = grade.startsWith("A")
      ? `Just validated my AI-generated code with @DeepSweepAI -- Grade ${grade}! Ship-ready.`
      : `Validated my code with @DeepSweepAI -- Grade ${grade} (${score}/100). Shipping safely.`;
    return `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(shareUrl)}`;
  }

  static getLinkedInUrl(shareUrl: string): string {
    return `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl)}`;
  }
}
