<?php
$pageTitle = mb_strimwidth($item['title'] ?? 'View Content', 0, 60, '…');
require __DIR__ . '/../layout/header.php';

$statusColor = ['draft' => 'warning', 'approved' => 'success', 'qa_failed' => 'danger', 'published' => 'primary'][$item['status']] ?? 'secondary';
$qaExtras    = $item['meta_extras'] ?? [];
$checks      = $item['checks_detail'] ?? [];
?>

<!-- Page Header -->
<div class="d-flex align-items-start gap-3 mb-4 flex-wrap">
  <a href="<?= BASE_URL ?>/content" class="btn btn-sm btn-light mt-1"><i class="bi bi-arrow-left"></i></a>
  <div class="flex-grow-1">
    <div class="d-flex align-items-center gap-2 flex-wrap mb-1">
      <h4 class="fw-bold mb-0"><?= htmlspecialchars($item['title']) ?></h4>
      <?php if (!empty($item['content_code'])): ?>
      <span class="badge bg-dark text-white font-monospace" style="font-size:11px;letter-spacing:.04em;"><?= htmlspecialchars($item['content_code']) ?></span>
      <?php endif; ?>
      <span class="badge bg-<?= $statusColor ?>-subtle text-<?= $statusColor ?>"><?= htmlspecialchars(ucfirst(str_replace('_', ' ', $item['status']))) ?></span>
    </div>
    <div class="text-muted small">
      <?= htmlspecialchars($item['business_name']) ?> &bull;
      <?= htmlspecialchars($item['page_type_name']) ?> &bull;
      <i class="bi bi-key me-1"></i><?= htmlspecialchars($item['primary_keyword']) ?>
    </div>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <?php if ($item['status'] !== 'approved'): ?>
    <form method="POST" action="<?= BASE_URL ?>/content/<?= $item['id'] ?>/approve">
      <button class="btn btn-success"><i class="bi bi-check2-circle me-1"></i>Approve</button>
    </form>
    <?php else: ?>
    <span class="btn btn-success disabled"><i class="bi bi-check2-circle me-1"></i>Approved</span>
    <?php endif; ?>
    <form method="POST" action="<?= BASE_URL ?>/content/<?= $item['id'] ?>/regenerate"
          onsubmit="return confirm('Regenerate from scratch? The existing version will be replaced.')">
      <button class="btn btn-outline-warning"><i class="bi bi-arrow-clockwise me-1"></i>Regenerate</button>
    </form>
    <div class="dropdown">
      <button class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown">
        <i class="bi bi-download me-1"></i>Export
      </button>
      <ul class="dropdown-menu dropdown-menu-end">
        <li><a class="dropdown-item" href="<?= BASE_URL ?>/content/<?= $item['id'] ?>/export/html"><i class="bi bi-file-code me-2"></i>HTML</a></li>
        <li><a class="dropdown-item" href="<?= BASE_URL ?>/content/<?= $item['id'] ?>/export/word"><i class="bi bi-file-word me-2"></i>Word (.doc)</a></li>
        <li><a class="dropdown-item" href="<?= BASE_URL ?>/content/<?= $item['id'] ?>/export/json"><i class="bi bi-filetype-json me-2"></i>JSON</a></li>
      </ul>
    </div>
    <form method="POST" action="<?= BASE_URL ?>/content/<?= $item['id'] ?>/delete" class="confirm-delete">
      <button class="btn btn-outline-danger"><i class="bi bi-trash"></i></button>
    </form>
  </div>
</div>

<div class="row g-4">

  <!-- ═══════════════════════════════════════════════════════════
       LEFT: Content Preview / Editor + Edit History
  ════════════════════════════════════════════════════════════ -->
  <div class="col-lg-8">

    <!-- Preview / Edit tabs -->
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header bg-white py-3 d-flex align-items-center justify-content-between">
        <div class="d-flex gap-1">
          <button class="btn btn-sm btn-primary" id="tab-preview" onclick="switchTab('preview')">
            <i class="bi bi-eye me-1"></i>Preview
          </button>
          <button class="btn btn-sm btn-outline-secondary" id="tab-edit" onclick="switchTab('edit')">
            <i class="bi bi-pencil me-1"></i>Edit HTML
          </button>
        </div>
        <div class="d-flex align-items-center gap-2">
          <span id="wc-badge" class="badge bg-secondary-subtle text-secondary" style="display:none;"></span>
          <button class="btn btn-sm btn-outline-secondary" id="copy-btn" onclick="copyContent()">
            <i class="bi bi-clipboard me-1"></i>Copy HTML
          </button>
          <span class="badge bg-<?= $statusColor ?>-subtle text-<?= $statusColor ?> px-3 py-2">
            <?= ucfirst(str_replace('_', ' ', $item['status'])) ?>
          </span>
        </div>
      </div>

      <!-- Preview pane -->
      <div class="card-body" id="pane-preview">
        <div class="content-preview" id="content-body">
          <?= $item['output'] ?>
        </div>
      </div>

      <!-- Edit pane -->
      <div class="card-body" id="pane-edit" style="display:none;">
        <form method="POST" action="<?= BASE_URL ?>/content/<?= $item['id'] ?>/save-edit" id="edit-form">
          <textarea class="form-control font-mono mb-3" name="content" id="edit-textarea"
                    rows="28" spellcheck="false"
                    oninput="updateWordCount(this.value)"><?= htmlspecialchars($item['output']) ?></textarea>
          <div class="d-flex gap-2 align-items-center">
            <input type="text" name="note" class="form-control form-control-sm"
                   placeholder="Edit note (optional, e.g. 'Fixed intro paragraph')" style="max-width:320px;">
            <button type="submit" class="btn btn-primary btn-sm">
              <i class="bi bi-floppy me-1"></i>Save Edit
            </button>
            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="switchTab('preview')">Cancel</button>
          </div>
        </form>
      </div>
    </div>

    <!-- Edit History -->
    <?php if (!empty($editHistory)): ?>
    <div class="accordion mb-4" id="historyAccordion">
      <div class="accordion-item border-0 shadow-sm">
        <h2 class="accordion-header">
          <button class="accordion-button collapsed fw-semibold" type="button"
                  data-bs-toggle="collapse" data-bs-target="#historyCollapse">
            <i class="bi bi-clock-history text-secondary me-2"></i>
            Edit History
            <span class="badge bg-secondary ms-2"><?= count($editHistory) ?></span>
          </button>
        </h2>
        <div id="historyCollapse" class="accordion-collapse collapse">
          <div class="accordion-body p-0">
            <table class="table table-sm table-hover mb-0">
              <thead class="table-light">
                <tr><th>Date</th><th>Words</th><th>Note</th><th></th></tr>
              </thead>
              <tbody>
                <?php foreach ($editHistory as $edit): ?>
                <tr>
                  <td class="small text-muted"><?= date('M j, Y H:i', strtotime($edit['created_at'])) ?></td>
                  <td><?= number_format($edit['word_count']) ?></td>
                  <td class="small"><?= htmlspecialchars($edit['edit_note'] ?? '—') ?></td>
                  <td>
                    <button class="btn btn-xs btn-outline-secondary py-0 px-2"
                            onclick="restoreEdit(<?= $edit['id'] ?>, <?= $item['id'] ?>)"
                            title="Restore this version">
                      <i class="bi bi-arrow-counterclockwise"></i>
                    </button>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <?php endif; ?>

  </div><!-- /col-lg-8 -->

  <!-- ═══════════════════════════════════════════════════════════
       RIGHT: QA + SEO Metrics + Tools + Meta
  ════════════════════════════════════════════════════════════ -->
  <div class="col-lg-4">

    <!-- QA Checklist -->
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-header bg-white py-3 d-flex align-items-center justify-content-between">
        <h6 class="fw-semibold mb-0">
          <i class="bi bi-shield-check text-<?= $item['qa_passed'] ? 'success' : 'danger' ?> me-2"></i>QA Checklist
        </h6>
        <span class="badge bg-<?= $item['qa_passed'] ? 'success' : 'danger' ?>-subtle text-<?= $item['qa_passed'] ? 'success' : 'danger' ?> px-3">
          <?= $item['qa_passed'] ? 'PASSED' : 'FAILED' ?>
        </span>
      </div>
      <div class="card-body p-0">
        <?php if (!empty($checks)): ?>
        <ul class="list-group list-group-flush">
          <?php foreach ($checks as $chk):
            $isInfo    = !empty($chk['info']);
            $icon      = $chk['passed'] ? 'check-circle-fill' : ($isInfo ? 'info-circle-fill' : 'x-circle-fill');
            $iconColor = $chk['passed'] ? 'success' : ($isInfo ? 'info' : 'danger');
          ?>
          <li class="list-group-item px-3 py-2 d-flex align-items-start gap-2 <?= (!$chk['passed'] && !$isInfo) ? 'bg-danger-subtle' : '' ?>">
            <i class="bi bi-<?= $icon ?> text-<?= $iconColor ?> mt-1 flex-shrink-0" style="font-size:13px;"></i>
            <div style="font-size:12.5px; min-width:0;">
              <div class="fw-semibold lh-1 mb-1"><?= htmlspecialchars($chk['name']) ?></div>
              <div class="text-muted" style="font-size:11px;">
                Need: <?= htmlspecialchars($chk['required']) ?>
              </div>
              <div class="<?= $chk['passed'] ? 'text-success' : ($isInfo ? 'text-info' : 'text-danger') ?>" style="font-size:11px;">
                Got: <?= htmlspecialchars($chk['actual']) ?>
              </div>
            </div>
          </li>
          <?php endforeach; ?>
        </ul>
        <?php else: ?>
        <div class="px-3 py-3">
          <?php if (!empty($item['issues_found'])): ?>
          <div class="small text-danger fw-semibold mb-1"><i class="bi bi-exclamation-triangle me-1"></i>Issues:</div>
          <ul class="mb-0 ps-3 small text-danger">
            <?php foreach ($item['issues_found'] as $issue): ?>
            <li><?= htmlspecialchars($issue) ?></li>
            <?php endforeach; ?>
          </ul>
          <?php else: ?>
          <div class="small text-success"><i class="bi bi-check-circle me-1"></i>All checks passed</div>
          <?php endif; ?>
          <div class="text-muted small mt-2">Re-generate to see full checklist.</div>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- SEO Metrics -->
    <?php
    $readability = (float)($item['readability_score'] ?? 0);
    $readColor   = $readability >= 70 ? 'success' : ($readability >= 50 ? 'primary' : ($readability >= 30 ? 'warning' : 'danger'));
    $readLabel   = $readability >= 70 ? 'Easy' : ($readability >= 50 ? 'Standard' : ($readability >= 30 ? 'Difficult' : 'Complex'));
    ?>
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-header bg-white py-3">
        <h6 class="fw-semibold mb-0"><i class="bi bi-bar-chart-line text-primary me-2"></i>SEO Metrics</h6>
      </div>
      <div class="card-body">
        <div class="row g-2">
          <div class="col-6">
            <div class="text-center p-2 rounded bg-<?= $readColor ?>-subtle">
              <div class="fw-bold fs-5 text-<?= $readColor ?>"><?= $readability ?: '—' ?></div>
              <div class="text-muted" style="font-size:10px;">Readability</div>
              <?php if ($readability): ?>
              <div class="text-<?= $readColor ?>" style="font-size:10px;"><?= $readLabel ?></div>
              <?php endif; ?>
            </div>
          </div>
          <div class="col-6">
            <div class="text-center p-2 rounded bg-light">
              <div class="fw-bold fs-5"><?= $item['avg_sentence_length'] ?: '—' ?></div>
              <div class="text-muted" style="font-size:10px;">Avg Sentence</div>
              <div class="text-muted" style="font-size:10px;">words</div>
            </div>
          </div>
          <div class="col-6">
            <div class="text-center p-2 rounded bg-light">
              <div class="fw-bold fs-5"><?= $item['paragraph_count'] ?: '—' ?></div>
              <div class="text-muted" style="font-size:10px;">Paragraphs</div>
            </div>
          </div>
          <div class="col-6">
            <div class="text-center p-2 rounded bg-light">
              <div class="fw-bold fs-5"><?= $item['unique_word_ratio'] ? $item['unique_word_ratio'] . '%' : '—' ?></div>
              <div class="text-muted" style="font-size:10px;">Vocabulary</div>
              <div class="text-muted" style="font-size:10px;">richness</div>
            </div>
          </div>
          <div class="col-6">
            <div class="text-center p-2 rounded bg-light">
              <div class="fw-bold fs-5"><?= number_format($item['word_count'] ?? 0) ?></div>
              <div class="text-muted" style="font-size:10px;">Words</div>
            </div>
          </div>
          <div class="col-6">
            <div class="text-center p-2 rounded bg-light">
              <div class="fw-bold fs-5"><?= ($item['keyword_density'] ?? 0) ?>%</div>
              <div class="text-muted" style="font-size:10px;">Keyword Density</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- AI Fix -->
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-header bg-white py-3">
        <h6 class="fw-semibold mb-0"><i class="bi bi-stars text-warning me-2"></i>AI Fix</h6>
      </div>
      <div class="card-body pb-2">
        <textarea id="ai-fix-instruction" class="form-control form-control-sm mb-2" rows="3"
                  placeholder="Describe what to fix, e.g. 'Make the intro more engaging' or 'Add a pricing section'"></textarea>
        <button class="btn btn-sm btn-warning w-100" onclick="runAiFix(<?= $item['id'] ?>)" id="btn-ai-fix">
          <i class="bi bi-stars me-1"></i>Apply AI Fix
        </button>
        <div id="result-ai-fix" class="mt-2"></div>
      </div>
    </div>

    <!-- Content Tools -->
    <div class="accordion border-0 shadow-sm mb-3" id="toolsAccordion">
      <div class="accordion-item border-0">
        <h2 class="accordion-header">
          <button class="accordion-button collapsed fw-semibold rounded-top" type="button"
                  data-bs-toggle="collapse" data-bs-target="#toolsCollapse" style="border-radius:12px 12px 0 0;">
            <i class="bi bi-tools text-warning me-2"></i>Content Tools
          </button>
        </h2>
        <div id="toolsCollapse" class="accordion-collapse collapse">
          <div class="accordion-body p-0">

            <!-- Meta Tags -->
            <div class="border-bottom p-3">
              <div class="d-flex align-items-center justify-content-between mb-2">
                <span class="fw-semibold small"><i class="bi bi-tags me-1"></i>Meta Tags</span>
                <button class="btn btn-xs btn-outline-primary py-0 px-2"
                        onclick="runTool('meta-tags', <?= $item['id'] ?>)" id="btn-meta-tags">
                  <?= !empty($qaExtras['meta_tags']) ? 'Regenerate' : 'Generate' ?>
                </button>
              </div>
              <div id="result-meta-tags">
                <?php if (!empty($qaExtras['meta_tags']) && empty($qaExtras['meta_tags']['parse_error'])): $mt = $qaExtras['meta_tags']; ?>
                <dl class="row mb-0" style="font-size:11.5px;">
                  <dt class="col-4 text-muted">Title Tag</dt>
                  <dd class="col-8"><?= htmlspecialchars($mt['title_tag'] ?? '') ?></dd>
                  <dt class="col-4 text-muted">Meta Desc</dt>
                  <dd class="col-8"><?= htmlspecialchars($mt['meta_description'] ?? '') ?></dd>
                  <dt class="col-4 text-muted">Focus KW</dt>
                  <dd class="col-8"><?= htmlspecialchars($mt['focus_keyword'] ?? '') ?></dd>
                </dl>
                <?php endif; ?>
              </div>
            </div>

            <!-- Schema Markup -->
            <div class="border-bottom p-3">
              <div class="d-flex align-items-center justify-content-between mb-2">
                <span class="fw-semibold small"><i class="bi bi-code-slash me-1"></i>Schema Markup</span>
                <button class="btn btn-xs btn-outline-primary py-0 px-2"
                        onclick="runTool('schema', <?= $item['id'] ?>)" id="btn-schema">
                  <?= !empty($qaExtras['schema_markup']) ? 'Regenerate' : 'Generate' ?>
                </button>
              </div>
              <div id="result-schema">
                <?php if (!empty($qaExtras['schema_markup'])): ?>
                <div class="position-relative">
                  <pre class="bg-dark text-light p-2 rounded small mb-0" style="font-size:10px;max-height:150px;overflow-y:auto;"><?= htmlspecialchars($qaExtras['schema_markup']) ?></pre>
                  <button class="btn btn-xs btn-outline-light position-absolute top-0 end-0 m-1 py-0 px-1"
                          onclick="copyText(document.getElementById('schema-pre').textContent)" style="font-size:10px;">
                    Copy
                  </button>
                </div>
                <?php endif; ?>
              </div>
            </div>

            <!-- Anchor Text -->
            <div class="border-bottom p-3">
              <div class="d-flex align-items-center justify-content-between mb-2">
                <span class="fw-semibold small"><i class="bi bi-link-45deg me-1"></i>Anchor Text</span>
                <button class="btn btn-xs btn-outline-primary py-0 px-2"
                        onclick="runTool('anchor-text', <?= $item['id'] ?>)" id="btn-anchor-text">
                  <?= !empty($qaExtras['anchor_text']) ? 'Regenerate' : 'Generate' ?>
                </button>
              </div>
              <div id="result-anchor-text">
                <?php if (!empty($qaExtras['anchor_text']['anchors'])): ?>
                <ul class="list-unstyled mb-0" style="font-size:11.5px;">
                  <?php foreach ($qaExtras['anchor_text']['anchors'] as $a): ?>
                  <li class="d-flex align-items-center gap-2 mb-1">
                    <span class="badge bg-secondary-subtle text-secondary" style="font-size:9px;"><?= htmlspecialchars($a['type'] ?? '') ?></span>
                    <span><?= htmlspecialchars($a['text'] ?? '') ?></span>
                  </li>
                  <?php endforeach; ?>
                </ul>
                <?php endif; ?>
              </div>
            </div>

            <!-- Image Suggestions -->
            <div class="border-bottom p-3">
              <div class="d-flex align-items-center justify-content-between mb-2">
                <span class="fw-semibold small"><i class="bi bi-image me-1"></i>Image Suggestions</span>
                <button class="btn btn-xs btn-outline-primary py-0 px-2"
                        onclick="runTool('images', <?= $item['id'] ?>)" id="btn-images">
                  <?= !empty($qaExtras['image_suggestions']) ? 'Regenerate' : 'Generate' ?>
                </button>
              </div>
              <div id="result-images">
                <?php if (!empty($qaExtras['image_suggestions']['images'])): ?>
                <?php foreach ($qaExtras['image_suggestions']['images'] as $img): ?>
                <div class="mb-2 p-2 bg-light rounded" style="font-size:11.5px;">
                  <span class="badge bg-info-subtle text-info me-1"><?= htmlspecialchars($img['position'] ?? '') ?></span>
                  <strong><?= htmlspecialchars($img['alt_text'] ?? '') ?></strong>
                  <div class="text-muted mt-1"><?= htmlspecialchars($img['description'] ?? '') ?></div>
                  <?php if (!empty($img['ai_prompt'])): ?>
                  <div class="text-primary mt-1" style="font-size:10px;font-style:italic;">AI: <?= htmlspecialchars($img['ai_prompt']) ?></div>
                  <?php endif; ?>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
              </div>
            </div>

            <!-- Internal Links -->
            <div class="p-3">
              <div class="d-flex align-items-center justify-content-between mb-2">
                <span class="fw-semibold small"><i class="bi bi-diagram-2 me-1"></i>Internal Links</span>
                <button class="btn btn-xs btn-outline-primary py-0 px-2"
                        onclick="loadInternalLinks(<?= $item['id'] ?>)" id="btn-internal-links">
                  Load
                </button>
              </div>
              <div id="result-internal-links"></div>
            </div>

          </div>
        </div>
      </div>
    </div>

    <!-- Meta Info -->
    <div class="card border-0 shadow-sm">
      <div class="card-header bg-white py-3">
        <h6 class="fw-semibold mb-0"><i class="bi bi-info-circle text-secondary me-2"></i>Generation Info</h6>
      </div>
      <div class="card-body">
        <dl class="row mb-0 small">
          <dt class="col-5 text-muted">Model</dt>
          <dd class="col-7"><?= htmlspecialchars($item['model_used'] ?? '—') ?></dd>
          <dt class="col-5 text-muted">Input Tokens</dt>
          <dd class="col-7"><?= number_format($item['input_tokens'] ?? 0) ?></dd>
          <dt class="col-5 text-muted">Output Tokens</dt>
          <dd class="col-7"><?= number_format($item['output_tokens'] ?? 0) ?></dd>
          <dt class="col-5 text-muted">Gen Time</dt>
          <dd class="col-7"><?= number_format(($item['generation_time_ms'] ?? 0) / 1000, 1) ?>s</dd>
          <dt class="col-5 text-muted">Retried</dt>
          <dd class="col-7"><?= (($item['retry_count'] ?? 0) > 0) ? 'Yes' : 'No' ?></dd>
          <dt class="col-5 text-muted">Search Intent</dt>
          <dd class="col-7"><?= htmlspecialchars($item['search_intent'] ?? '—') ?></dd>
          <dt class="col-5 text-muted">Created</dt>
          <dd class="col-7"><?= date('M j, Y H:i', strtotime($item['created_at'])) ?></dd>
          <?php if (!empty($item['content_angle'])): ?>
          <dt class="col-5 text-muted">Angle</dt>
          <dd class="col-7 small"><?= htmlspecialchars(mb_strimwidth($item['content_angle'], 0, 60, '…')) ?></dd>
          <?php endif; ?>
        </dl>
      </div>
    </div>

  </div><!-- /col-lg-4 -->
</div>

<?php
$contentId = (int)$item['id'];
$extraJs = <<<JS
<script>
// ── Tab switching ─────────────────────────────────────────
function switchTab(tab) {
  document.getElementById('pane-preview').style.display = tab === 'preview' ? '' : 'none';
  document.getElementById('pane-edit').style.display    = tab === 'edit'    ? '' : 'none';
  document.getElementById('tab-preview').className = 'btn btn-sm ' + (tab==='preview' ? 'btn-primary' : 'btn-outline-secondary');
  document.getElementById('tab-edit').className    = 'btn btn-sm ' + (tab==='edit'    ? 'btn-primary' : 'btn-outline-secondary');
  document.getElementById('wc-badge').style.display = tab === 'edit' ? '' : 'none';
  if (tab === 'edit') updateWordCount(document.getElementById('edit-textarea').value);
}

function updateWordCount(html) {
  const text  = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
  const words = text ? text.split(' ').length : 0;
  const badge = document.getElementById('wc-badge');
  badge.textContent = words.toLocaleString() + ' words';
  badge.style.display = '';
}

// ── Copy ─────────────────────────────────────────────────
function copyContent() {
  navigator.clipboard.writeText(document.getElementById('content-body').innerHTML).then(() => {
    const btn = document.getElementById('copy-btn');
    btn.innerHTML = '<i class="bi bi-check me-1"></i>Copied!';
    setTimeout(() => btn.innerHTML = '<i class="bi bi-clipboard me-1"></i>Copy HTML', 2000);
  });
}
function copyText(text) {
  navigator.clipboard.writeText(text).then(() => showToast('Copied!', 'success'));
}

// ── Content Tools AJAX ────────────────────────────────────
const TOOL_LABELS = {
  'meta-tags':    'Generating meta tags…',
  'schema':       'Generating schema markup…',
  'anchor-text':  'Generating anchor text…',
  'images':       'Generating image suggestions…',
};

function runTool(tool, contentId) {
  const btn = document.getElementById('btn-' + tool);
  const resultDiv = document.getElementById('result-' + tool);
  const origText = btn.textContent;
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
  resultDiv.innerHTML = '<div class="text-muted small py-1">' + (TOOL_LABELS[tool] || 'Working…') + '</div>';

  fetch(BASE_URL + '/api/content/' + contentId + '/extras/' + tool, { method: 'POST' })
    .then(r => r.json())
    .then(data => {
      btn.disabled = false;
      btn.textContent = 'Regenerate';
      if (data.success) {
        renderToolResult(tool, data.data);
      } else {
        resultDiv.innerHTML = '<div class="text-danger small">' + (data.message || 'Error') + '</div>';
      }
    })
    .catch(err => {
      btn.disabled = false;
      btn.textContent = origText;
      resultDiv.innerHTML = '<div class="text-danger small">Network error</div>';
    });
}

function renderToolResult(tool, data) {
  const div = document.getElementById('result-' + tool);
  if (tool === 'meta-tags') {
    div.innerHTML = '<dl class="row mb-0" style="font-size:11.5px;">'
      + '<dt class="col-4 text-muted">Title Tag</dt><dd class="col-8">' + escH(data.title_tag||'') + '</dd>'
      + '<dt class="col-4 text-muted">Meta Desc</dt><dd class="col-8">' + escH(data.meta_description||'') + '</dd>'
      + '<dt class="col-4 text-muted">OG Title</dt><dd class="col-8">' + escH(data.og_title||'') + '</dd>'
      + '<dt class="col-4 text-muted">Focus KW</dt><dd class="col-8">' + escH(data.focus_keyword||'') + '</dd>'
      + '</dl>';
  } else if (tool === 'schema') {
    const schema = data.schema || '';
    div.innerHTML = '<div class="position-relative">'
      + '<pre id="schema-pre" class="bg-dark text-light p-2 rounded small mb-0" style="font-size:10px;max-height:150px;overflow-y:auto;">' + escH(schema) + '</pre>'
      + '<button class="btn btn-outline-light position-absolute top-0 end-0 m-1 py-0 px-1" style="font-size:10px;"'
      + ' onclick="copyText(document.getElementById(\'schema-pre\').textContent)">Copy</button>'
      + '</div>';
  } else if (tool === 'anchor-text') {
    const anchors = data.anchors || [];
    div.innerHTML = '<ul class="list-unstyled mb-0" style="font-size:11.5px;">'
      + anchors.map(function(a) {
          return '<li class="d-flex align-items-center gap-2 mb-1">'
            + '<span class="badge bg-secondary-subtle text-secondary" style="font-size:9px;">' + escH(a.type||'') + '</span>'
            + '<span>' + escH(a.text||'') + '</span></li>';
        }).join('')
      + '</ul>';
  } else if (tool === 'images') {
    const images = data.images || [];
    div.innerHTML = images.map(function(img) {
      return '<div class="mb-2 p-2 bg-light rounded" style="font-size:11.5px;">'
        + '<span class="badge bg-info-subtle text-info me-1">' + escH(img.position||'') + '</span>'
        + '<strong>' + escH(img.alt_text||'') + '</strong>'
        + '<div class="text-muted mt-1">' + escH(img.description||'') + '</div>'
        + '<div class="text-primary mt-1" style="font-size:10px;font-style:italic;">AI: ' + escH(img.ai_prompt||'') + '</div>'
        + '</div>';
    }).join('');
  }
}

function loadInternalLinks(contentId) {
  const btn = document.getElementById('btn-internal-links');
  const div = document.getElementById('result-internal-links');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

  fetch(BASE_URL + '/api/content/' + contentId + '/extras/internal-links')
    .then(r => r.json())
    .then(data => {
      btn.disabled = false;
      btn.textContent = 'Reload';
      if (!data.success || !data.data.length) {
        div.innerHTML = '<div class="text-muted small">No other content found for this project yet.</div>';
        return;
      }
      div.innerHTML = '<ul class="list-unstyled mb-0" style="font-size:11.5px;">'
        + data.data.map(function(link) {
            const url = link.content_id ? BASE_URL + '/content/' + link.content_id : '#';
            return '<li class="mb-1 d-flex align-items-start gap-1">'
              + '<i class="bi bi-link text-muted mt-1" style="font-size:11px;"></i>'
              + '<div>'
              + '<a href="' + url + '" target="_blank" class="text-decoration-none">' + escH(link.title) + '</a>'
              + '<div class="text-muted" style="font-size:10px;">' + escH(link.primary_keyword) + ' &bull; ' + escH(link.page_type) + '</div>'
              + '</div></li>';
          }).join('')
        + '</ul>';
    })
    .catch(() => {
      btn.disabled = false;
      btn.textContent = 'Load';
      div.innerHTML = '<div class="text-danger small">Network error</div>';
    });
}

// ── Restore edit version ──────────────────────────────────
function restoreEdit(editId, contentId) {
  if (!confirm('Restore this version? Current content will be saved to history first.')) return;
  fetch(BASE_URL + '/api/content/restore-edit', {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    body: JSON.stringify({ edit_id: editId, content_id: contentId })
  })
  .then(r => r.json())
  .then(data => {
    if (data.success) { showToast('Version restored', 'success'); setTimeout(() => location.reload(), 800); }
    else showToast(data.message || 'Failed to restore', 'danger');
  });
}

function escH(s) {
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// ── AI Fix ────────────────────────────────────────────────
function runAiFix(contentId) {
  const instruction = document.getElementById('ai-fix-instruction').value.trim();
  if (!instruction) { showToast('Enter a fix instruction first', 'warning'); return; }
  const btn = document.getElementById('btn-ai-fix');
  const resultDiv = document.getElementById('result-ai-fix');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Applying fix…';
  resultDiv.innerHTML = '';

  fetch(BASE_URL + '/api/content/' + contentId + '/ai-fix', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({ instruction: instruction })
  })
  .then(r => r.json())
  .then(data => {
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-stars me-1"></i>Apply AI Fix';
    if (data.success) {
      document.getElementById('content-body').innerHTML = data.data.output || '';
      document.getElementById('edit-textarea').value = data.data.output || '';
      const passed = data.data.qa && data.data.qa.passed;
      resultDiv.innerHTML = '<div class="alert alert-' + (passed ? 'success' : 'warning') + ' py-2 px-3 mb-0 small">'
        + '<i class="bi bi-' + (passed ? 'check-circle' : 'exclamation-triangle') + ' me-1"></i>'
        + (passed ? 'Fix applied — QA passed.' : 'Fix applied — QA issues remain. Review before approving.')
        + '</div>';
      showToast('AI fix applied', passed ? 'success' : 'warning');
      setTimeout(() => location.reload(), 1500);
    } else {
      resultDiv.innerHTML = '<div class="text-danger small">' + escH(data.message || 'Fix failed') + '</div>';
    }
  })
  .catch(() => {
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-stars me-1"></i>Apply AI Fix';
    resultDiv.innerHTML = '<div class="text-danger small">Network error</div>';
  });
}
</script>
JS;
require __DIR__ . '/../layout/footer.php';
?>
