// ── Debrid Auth & Addon URL HTML pages ──
// Rendered at:
//   GET /debrid/auth/form/{code}   — OAuth page or API key form
//   GET /addon/url/form/{code}     — Addon manifest URL entry form

// ── Debrid OAuth page (shows user code + verification URL + QR) ──

export function renderOAuthPage(params: {
  code: string;
  service: string;
  userCode: string;
  verificationUrl: string;
  status: string;
  appName: string;
  publicHost: string;
  error?: string | null;
}): string {
  const { code, service, userCode, verificationUrl, status, appName, publicHost, error } = params;
  const serviceLabel = serviceLabelFor(service);
  const qrDataUrl = `https://chart.googleapis.com/chart?chs=240x240&cht=qr&chl=${encodeURIComponent(verificationUrl)}&choe=UTF-8`;
  const pollingInterval = 3000;

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Authenticate ${escapeHtml(serviceLabel)} · ${escapeHtml(appName)}</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: #0f0f0f; color: #e0e0e0;
      min-height: 100vh; display: flex; flex-direction: column; align-items: center;
      padding: 24px; line-height: 1.5;
    }
    .container { max-width: 480px; width: 100%; }
    .card {
      background: #1a1a2e; border-radius: 16px; padding: 32px 24px;
      margin-top: 24px; box-shadow: 0 8px 32px rgba(0,0,0,0.4);
    }
    h1 { font-size: 24px; font-weight: 700; color: #fff; margin-bottom: 8px; }
    .subtitle { color: #888; font-size: 14px; margin-bottom: 24px; }
    .service-name { font-size: 20px; font-weight: 600; color: #00a3ff; margin-bottom: 16px; }
    .status-row { display: flex; align-items: center; gap: 12px; margin-bottom: 24px; }
    .badge {
      display: inline-block; padding: 4px 12px; border-radius: 99px;
      font-size: 12px; font-weight: 600; text-transform: uppercase;
    }
    .badge.active { background: #003366; color: #00a3ff; }
    .badge.completed { background: #003300; color: #00ff88; }
    .badge.cancelled { background: #330000; color: #ff4444; }
    .badge.error { background: #330000; color: #ff4444; }
    .user-code {
      display: flex; justify-content: center; margin: 24px 0;
      font-size: 40px; font-weight: 800; letter-spacing: 8px;
      color: #fff; font-family: 'Courier New', monospace;
      background: #121220; border-radius: 12px; padding: 16px;
      border: 2px dashed #333;
    }
    .qr-container {
      display: flex; justify-content: center; margin: 16px 0;
    }
    .qr-container img {
      border-radius: 12px; background: #fff; padding: 8px;
    }
    .instructions {
      margin: 16px 0; font-size: 14px; color: #aaa; text-align: center;
    }
    .instructions ol {
      text-align: left; margin-top: 8px; padding-left: 20px;
    }
    .instructions li { margin-bottom: 8px; }
    .verification-link {
      display: block; text-align: center; margin: 12px 0;
      font-size: 16px; font-weight: 600;
    }
    .verification-link a { color: #00a3ff; text-decoration: none; }
    .verification-link a:hover { text-decoration: underline; }
    .btn {
      display: inline-flex; align-items: center; justify-content: center;
      padding: 14px 24px; border-radius: 12px; border: none;
      font-size: 16px; font-weight: 600; cursor: pointer; text-decoration: none;
      width: 100%; transition: opacity 0.2s;
    }
    .btn:active { opacity: 0.8; }
    .btn-secondary { background: #2a2a4a; color: #e0e0e0; margin-top: 12px; }
    .btn-primary { background: #00a3ff; color: #fff; }
    .error-text { color: #ff4444; font-size: 13px; margin-top: 8px; }
    .success-text { color: #00ff88; font-size: 13px; margin-top: 8px; }
    .spinner {
      display: inline-block; width: 16px; height: 16px;
      border: 2px solid #555; border-top-color: #fff;
      border-radius: 50%; animation: spin 0.8s linear infinite;
      margin-right: 8px; vertical-align: middle;
    }
    @keyframes spin { to { transform: rotate(360deg); } }
    .footer { margin-top: 24px; text-align: center; font-size: 12px; color: #555; }
    .pulse { animation: pulse 2s infinite; }
    @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.7; } }
  </style>
</head>
<body>
  <div class="container">
    <div class="card">
      <div class="subtitle">${escapeHtml(appName)} · Debrid Authentication</div>
      <h1>Authenticate</h1>
      <div class="service-name">${escapeHtml(serviceLabel)}</div>

      <div class="status-row">
        <span>Status:</span>
        <span class="badge ${status}">${statusBadgeText(status)}</span>
      </div>

      ${error ? `<div class="error-text">${escapeHtml(error)}</div>` : ""}

      ${status === "active" ? `
        <div class="qr-container">
          <img src="${escapeHtml(qrDataUrl)}" alt="QR Code" width="240" height="240" />
        </div>

        <div class="user-code pulse">${escapeHtml(userCode)}</div>

        <div class="instructions">
          <p><strong>How to authorize:</strong></p>
          <ol>
            <li>Open <strong>${escapeHtml(verificationUrl)}</strong> on your device</li>
            <li>Enter the code: <strong>${escapeHtml(userCode)}</strong></li>
            <li>Authorize ${escapeHtml(appName)}</li>
          </ol>
        </div>

        <div class="verification-link">
          <a href="${escapeHtml(verificationUrl)}" target="_blank">${escapeHtml(verificationUrl)}</a>
        </div>

        <p class="instructions" style="margin-top:16px;">
          <span class="spinner"></span> Waiting for authorization...
        </p>
      ` : status === "completed" ? `
        <div class="success-text">✓ Authorization complete! You can close this page and return to the app.</div>
      ` : status === "error" ? `
        <div class="error-text">✗ Authorization failed. Please try again from the app.</div>
      ` : `
        <div class="error-text">✗ Session expired or cancelled. Please start again from the app.</div>
      `}

      ${status !== "completed" ? `
        <button class="btn btn-secondary" onclick="cancelSession()">Cancel</button>
      ` : ""}
    </div>
    <div class="footer">
      ${escapeHtml(appName)} · Auth code: ${escapeHtml(code)}<br>
      This page expires in 15 minutes.
    </div>
  </div>

  <script>
    const code = ${JSON.stringify(code)};

    ${status === "active" ? `
    // Poll for OAuth completion
    async function pollStatus() {
      try {
        const r = await fetch('/debrid/auth/status/' + code);
        const data = await r.json();
        if (data.status === 'completed') {
          window.location.reload();
        } else if (data.status === 'error' || data.status === 'cancelled') {
          window.location.reload();
        }
      } catch(e) {}
    }
    setInterval(pollStatus, ${pollingInterval});
    ` : ""}

    // Cancel session
    async function cancelSession() {
      try {
        await fetch('/debrid/auth/cancel/' + code);
        window.location.reload();
      } catch(e) {}
    }
  </script>
</body>
</html>`;
}

// ── Debrid API key entry form ──

export function renderApiKeyForm(params: {
  code: string;
  service: string;
  authType: string;
  status: string;
  appName: string;
  publicHost: string;
  error?: string | null;
}): string {
  const { code, service, authType, status, appName, publicHost, error } = params;
  const serviceLabel = serviceLabelFor(service);

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Enter API Key · ${escapeHtml(appName)}</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: #0f0f0f; color: #e0e0e0;
      min-height: 100vh; display: flex; flex-direction: column; align-items: center;
      padding: 24px; line-height: 1.5;
    }
    .container { max-width: 480px; width: 100%; }
    .card {
      background: #1a1a2e; border-radius: 16px; padding: 32px 24px;
      margin-top: 24px; box-shadow: 0 8px 32px rgba(0,0,0,0.4);
    }
    h1 { font-size: 24px; font-weight: 700; color: #fff; margin-bottom: 8px; }
    .subtitle { color: #888; font-size: 14px; margin-bottom: 24px; }
    .service-name { font-size: 20px; font-weight: 600; color: #00a3ff; margin-bottom: 16px; }
    .status-row { display: flex; align-items: center; gap: 12px; margin-bottom: 24px; }
    .badge {
      display: inline-block; padding: 4px 12px; border-radius: 99px;
      font-size: 12px; font-weight: 600; text-transform: uppercase;
    }
    .badge.pending { background: #2a2a4a; color: #888; }
    .badge.active { background: #003366; color: #00a3ff; }
    .badge.completed { background: #003300; color: #00ff88; }
    .badge.cancelled { background: #330000; color: #ff4444; }
    .badge.error { background: #330000; color: #ff4444; }
    .input-group { margin-top: 16px; }
    label { display: block; font-size: 14px; color: #888; margin-bottom: 8px; }
    input[type="text"], input[type="password"] {
      width: 100%; padding: 12px 16px; border-radius: 12px; border: 1px solid #333;
      background: #121220; color: #e0e0e0; font-size: 14px; font-family: monospace;
      transition: border-color 0.2s;
    }
    input[type="text"]:focus, input[type="password"]:focus {
      outline: none; border-color: #00a3ff;
    }
    .help-text { font-size: 12px; color: #666; margin-top: 8px; }
    .error-text { color: #ff4444; font-size: 13px; margin-top: 8px; }
    .success-text { color: #00ff88; font-size: 13px; margin-top: 8px; }
    .btn {
      display: inline-flex; align-items: center; justify-content: center;
      padding: 14px 24px; border-radius: 12px; border: none;
      font-size: 16px; font-weight: 600; cursor: pointer; text-decoration: none;
      width: 100%; transition: opacity 0.2s;
    }
    .btn:active { opacity: 0.8; }
    .btn-primary { background: #00a3ff; color: #fff; }
    .btn-success { background: #00cc66; color: #fff; }
    .btn-secondary { background: #2a2a4a; color: #e0e0e0; margin-top: 12px; }
    .btn:disabled { opacity: 0.4; cursor: not-allowed; }
    .footer { margin-top: 24px; text-align: center; font-size: 12px; color: #555; }
  </style>
</head>
<body>
  <div class="container">
    <div class="card">
      <div class="subtitle">${escapeHtml(appName)} · API Key Authentication</div>
      <h1>Enter API Key</h1>
      <div class="service-name">${escapeHtml(serviceLabel)}</div>

      <div class="status-row">
        <span>Status:</span>
        <span class="badge ${status}">${statusBadgeText(status)}</span>
      </div>

      ${error ? `<div class="error-text">${escapeHtml(error)}</div>` : ""}

      <div class="help-text" style="margin-bottom:16px;">
        To authenticate with ${escapeHtml(serviceLabel)}, enter your API key below.
        You can find your API key in your ${escapeHtml(serviceLabel)} account dashboard.
      </div>

      ${status === "pending" || status === "active" ? `
        <div class="input-group">
          <label for="apiKey">API Key</label>
          <input type="password" id="apiKey" placeholder="Paste your API key here" autocomplete="off" spellcheck="false" />
          <button class="btn btn-success" id="submitBtn" onclick="submitKey()">Submit</button>
          <p class="help-text" id="statusText"></p>
        </div>
      ` : status === "completed" ? `
        <div class="success-text">✓ Authentication complete! You can close this page and return to the app.</div>
      ` : `
        <div class="error-text">✗ Session expired or cancelled. Please start again from the app.</div>
      `}

      ${status !== "completed" ? `
        <button class="btn btn-secondary" onclick="cancelSession()">Cancel</button>
      ` : ""}
    </div>
    <div class="footer">
      ${escapeHtml(appName)} · Auth code: ${escapeHtml(code)}<br>
      This page expires in 15 minutes.
    </div>
  </div>

  <script>
    const code = ${JSON.stringify(code)};

    // Submit API key
    async function submitKey() {
      const key = document.getElementById('apiKey').value.trim();
      if (!key) {
        document.getElementById('statusText').textContent = 'Please enter an API key';
        return;
      }
      document.getElementById('submitBtn').disabled = true;
      document.getElementById('statusText').textContent = 'Submitting...';
      try {
        const r = await fetch('/debrid/auth/submit/' + code, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ apiKey: key }),
        });
        const data = await r.json();
        if (data.status === 'completed') {
          document.getElementById('statusText').className = 'success-text';
          document.getElementById('statusText').textContent = '✓ Authentication complete!';
          setTimeout(() => window.location.reload(), 1500);
        } else {
          document.getElementById('statusText').className = 'error-text';
          document.getElementById('statusText').textContent = data.error || 'Submission failed';
          document.getElementById('submitBtn').disabled = false;
        }
      } catch(e) {
        document.getElementById('statusText').className = 'error-text';
        document.getElementById('statusText').textContent = 'Network error';
        document.getElementById('submitBtn').disabled = false;
      }
    }

    // Cancel session
    async function cancelSession() {
      try {
        await fetch('/debrid/auth/cancel/' + code);
        window.location.reload();
      } catch(e) {}
    }
  </script>
</body>
</html>`;
}

// ── Addon URL entry form ──

export function renderAddonUrlForm(params: {
  code: string;
  status: string;
  manifestUrl?: string | null;
  validatedManifestOk?: boolean | null;
  manifestName?: string | null;
  appName: string;
  publicHost: string;
  error?: string | null;
}): string {
  const { code, status, manifestUrl, validatedManifestOk, manifestName, appName, publicHost, error } = params;

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Enter Addon URL · ${escapeHtml(appName)}</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: #0f0f0f; color: #e0e0e0;
      min-height: 100vh; display: flex; flex-direction: column; align-items: center;
      padding: 24px; line-height: 1.5;
    }
    .container { max-width: 480px; width: 100%; }
    .card {
      background: #1a1a2e; border-radius: 16px; padding: 32px 24px;
      margin-top: 24px; box-shadow: 0 8px 32px rgba(0,0,0,0.4);
    }
    h1 { font-size: 24px; font-weight: 700; color: #fff; margin-bottom: 8px; }
    .subtitle { color: #888; font-size: 14px; margin-bottom: 24px; }
    .status-row { display: flex; align-items: center; gap: 12px; margin-bottom: 24px; }
    .badge {
      display: inline-block; padding: 4px 12px; border-radius: 99px;
      font-size: 12px; font-weight: 600; text-transform: uppercase;
    }
    .badge.pending { background: #2a2a4a; color: #888; }
    .badge.active { background: #003366; color: #00a3ff; }
    .badge.completed { background: #003300; color: #00ff88; }
    .badge.cancelled { background: #330000; color: #ff4444; }
    .badge.error { background: #330000; color: #ff4444; }
    .input-group { margin-top: 16px; }
    label { display: block; font-size: 14px; color: #888; margin-bottom: 8px; }
    input[type="url"] {
      width: 100%; padding: 12px 16px; border-radius: 12px; border: 1px solid #333;
      background: #121220; color: #e0e0e0; font-size: 14px;
      transition: border-color 0.2s;
    }
    input[type="url"]:focus { outline: none; border-color: #00a3ff; }
    .help-text { font-size: 12px; color: #666; margin-top: 8px; }
    .error-text { color: #ff4444; font-size: 13px; margin-top: 8px; }
    .success-text { color: #00ff88; font-size: 13px; margin-top: 8px; }
    .btn {
      display: inline-flex; align-items: center; justify-content: center;
      padding: 14px 24px; border-radius: 12px; border: none;
      font-size: 16px; font-weight: 600; cursor: pointer; text-decoration: none;
      width: 100%; transition: opacity 0.2s;
    }
    .btn:active { opacity: 0.8; }
    .btn-primary { background: #00a3ff; color: #fff; }
    .btn-success { background: #00cc66; color: #fff; }
    .btn-secondary { background: #2a2a4a; color: #e0e0e0; margin-top: 12px; }
    .btn:disabled { opacity: 0.4; cursor: not-allowed; }
    .footer { margin-top: 24px; text-align: center; font-size: 12px; color: #555; }
    .manifest-info {
      background: #121220; border-radius: 12px; padding: 16px; margin: 16px 0;
      border: 1px solid #333;
    }
    .manifest-info .name { font-size: 16px; font-weight: 600; color: #00ff88; }
    .manifest-info .url { font-size: 12px; color: #888; word-break: break-all; margin-top: 4px; }
  </style>
</head>
<body>
  <div class="container">
    <div class="card">
      <div class="subtitle">${escapeHtml(appName)} · Addon URL Entry</div>
      <h1>Enter Addon URL</h1>

      <div class="status-row">
        <span>Status:</span>
        <span class="badge ${status}">${statusBadgeText(status)}</span>
      </div>

      <div class="help-text" style="margin-bottom:16px;">
        Enter the URL of the addon's manifest.json to validate and use it.
      </div>

      ${error ? `<div class="error-text">${escapeHtml(error)}</div>` : ""}

      ${validatedManifestOk && manifestName ? `
        <div class="manifest-info">
          <div class="name">✓ ${escapeHtml(manifestName)}</div>
          ${manifestUrl ? `<div class="url">${escapeHtml(manifestUrl)}</div>` : ""}
        </div>
      ` : ""}

      ${status === "pending" || status === "active" ? `
        <div class="input-group">
          <label for="manifestUrl">Manifest URL</label>
          <input type="url" id="manifestUrl" placeholder="https://example.com/manifest.json" spellcheck="false" />
          <button class="btn btn-success" id="submitBtn" onclick="submitUrl()">Submit & Validate</button>
          <p class="help-text" id="statusText"></p>
        </div>
      ` : status === "completed" ? `
        <div class="success-text">✓ Addon URL validated successfully! You can close this page and return to the app.</div>
      ` : status === "error" ? `
        <div class="error-text">✗ Validation failed. Please try again from the app.</div>
      ` : `
        <div class="error-text">✗ Session expired or cancelled. Please start again from the app.</div>
      `}

      ${status !== "completed" ? `
        <button class="btn btn-secondary" onclick="cancelSession()">Cancel</button>
      ` : ""}
    </div>
    <div class="footer">
      ${escapeHtml(appName)} · URL code: ${escapeHtml(code)}<br>
      This page expires in 15 minutes.
    </div>
  </div>

  <script>
    const code = ${JSON.stringify(code)};

    ${status === "pending" || status === "active" ? `
    // Poll status (in case phone opens it while user has it open)
    async function pollStatus() {
      try {
        const r = await fetch('/addon/url/status/' + code);
        const data = await r.json();
        if (data.status === 'completed' || data.status === 'error' || data.status === 'cancelled') {
          window.location.reload();
        }
      } catch(e) {}
    }
    setInterval(pollStatus, 3000);
    ` : ""}

    // Submit addon URL
    async function submitUrl() {
      const url = document.getElementById('manifestUrl').value.trim();
      if (!url) {
        document.getElementById('statusText').textContent = 'Please enter a manifest URL';
        return;
      }
      document.getElementById('submitBtn').disabled = true;
      document.getElementById('statusText').textContent = 'Validating...';
      try {
        const r = await fetch('/addon/url/submit/' + code, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ manifestUrl: url }),
        });
        const data = await r.json();
        if (data.status === 'completed') {
          document.getElementById('statusText').className = 'success-text';
          document.getElementById('statusText').textContent = '✓ Validated! Addon: ' + (data.manifestName || url);
          setTimeout(() => window.location.reload(), 1500);
        } else {
          document.getElementById('statusText').className = 'error-text';
          document.getElementById('statusText').textContent = data.error || 'Validation failed';
          document.getElementById('submitBtn').disabled = false;
        }
      } catch(e) {
        document.getElementById('statusText').className = 'error-text';
        document.getElementById('statusText').textContent = 'Network error';
        document.getElementById('submitBtn').disabled = false;
      }
    }

    // Cancel session
    async function cancelSession() {
      try {
        await fetch('/addon/url/cancel/' + code);
        window.location.reload();
      } catch(e) {}
    }
  </script>
</body>
</html>`;
}

// ═══════════════════════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════════════════════

function serviceLabelFor(service: string): string {
  const labels: Record<string, string> = {
    realdebrid: "Real-Debrid",
    premiumize: "Premiumize",
    torbox: "TorBox",
    alldebrid: "AllDebrid",
    debrider: "DebridLink",
    offcloud: "Offcloud",
  };
  return labels[service] || service;
}

function statusBadgeText(status: string): string {
  const labels: Record<string, string> = {
    pending: "⏳ Waiting",
    active: "📱 Active",
    completed: "✅ Done",
    cancelled: "✗ Cancelled",
    error: "⚠ Error",
  };
  return labels[status] || status;
}

function escapeHtml(str: string): string {
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
    .replace(/\"/g, "&quot;").replace(/'/g, "&#039;");
}
