<?php $pageTitle = 'AI Topic Generator'; require __DIR__ . '/../layout/header.php'; ?>

<div class="d-flex align-items-center gap-3 mb-4">
  <div>
    <h4 class="fw-bold mb-0"><i class="bi bi-stars text-warning me-2"></i>AI Topic Generator</h4>
    <p class="text-muted small mb-0">Enter seed keywords — AI generates ready-to-use topic briefs in bulk</p>
  </div>
</div>

<div class="row g-4">

  <!-- Input Panel -->
  <div class="col-lg-4">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header bg-white py-3">
        <h6 class="fw-semibold mb-0"><i class="bi bi-pencil-square text-primary me-2"></i>Generate Settings</h6>
      </div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label fw-medium">Project <span class="text-danger">*</span></label>
          <select class="form-select" id="project-select" required>
            <option value="">Select project…</option>
            <?php foreach ($projects as $p): ?>
            <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['business_name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label fw-medium">Page Type <span class="text-danger">*</span></label>
          <select class="form-select" id="pagetype-select" required>
            <option value="">Select page type…</option>
            <?php foreach ($pageTypes as $pt): ?>
            <option value="<?= $pt['id'] ?>"><?= htmlspecialchars($pt['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label fw-medium">Seed Keywords <span class="text-danger">*</span></label>
          <textarea class="form-control font-mono" id="seed-keywords" rows="8"
                    placeholder="One keyword per line, e.g.&#10;mosquito nets for balcony&#10;safety nets for kids&#10;bird netting for garden"></textarea>
          <div class="form-text">Each keyword generates its own set of topics.</div>
        </div>

        <div class="mb-4">
          <label class="form-label fw-medium">Topics per Keyword</label>
          <select class="form-select" id="count-per-kw">
            <option value="5">5 topics</option>
            <option value="10" selected>10 topics</option>
            <option value="15">15 topics</option>
          </select>
        </div>

        <button class="btn btn-primary w-100" id="generate-btn" onclick="generateTopics()">
          <i class="bi bi-stars me-2"></i>Generate Topics
        </button>
        <div class="text-muted small text-center mt-2">Takes 15–30 seconds depending on keyword count</div>
      </div>
    </div>
  </div>

  <!-- Results Panel -->
  <div class="col-lg-8">
    <div class="card border-0 shadow-sm">
      <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-list-check text-success me-2"></i>Generated Topics</h6>
        <div class="d-flex align-items-center gap-2" id="results-actions" style="display:none!important;">
          <span class="badge bg-success-subtle text-success" id="count-badge"></span>
          <button class="btn btn-sm btn-outline-secondary" onclick="selectAll(true)">Select All</button>
          <button class="btn btn-sm btn-outline-secondary" onclick="selectAll(false)">Deselect All</button>
          <button class="btn btn-sm btn-success" id="save-btn" onclick="saveTopics()">
            <i class="bi bi-floppy me-1"></i>Save Selected
          </button>
        </div>
      </div>
      <div class="card-body" id="results-body">
        <div class="text-center text-muted py-5" id="empty-state">
          <i class="bi bi-stars fs-1 d-block mb-3 text-warning opacity-50"></i>
          <div class="fw-semibold mb-1">Enter seed keywords and click Generate</div>
          <div class="small">AI will suggest complete topic briefs with keywords, search intent and content angles</div>
        </div>
        <div id="spinner-state" style="display:none;" class="text-center py-5">
          <div class="spinner-border text-primary mb-3" style="width:2.5rem;height:2.5rem;"></div>
          <div class="fw-semibold" id="spinner-msg">Generating topics…</div>
          <div class="text-muted small mt-1">Please wait, this may take 20–30 seconds</div>
        </div>
        <div id="table-state" style="display:none;">
          <div class="table-responsive">
            <table class="table table-hover mb-0" id="topics-table">
              <thead class="table-light">
                <tr>
                  <th style="width:36px;"><input type="checkbox" class="form-check-input" onchange="selectAll(this.checked)"></th>
                  <th>Title</th>
                  <th>Primary Keyword</th>
                  <th>Intent</th>
                  <th>Content Angle</th>
                </tr>
              </thead>
              <tbody id="topics-tbody"></tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

<?php
$extraJs = <<<'JS'
<script>
let generatedTopics = [];

function generateTopics() {
  const projectId  = document.getElementById('project-select').value;
  const pageTypeId = document.getElementById('pagetype-select').value;
  const rawKws     = document.getElementById('seed-keywords').value.trim();
  const countPerKw = parseInt(document.getElementById('count-per-kw').value);

  if (!projectId)  { showToast('Select a project', 'warning'); return; }
  if (!pageTypeId) { showToast('Select a page type', 'warning'); return; }
  if (!rawKws)     { showToast('Enter at least one seed keyword', 'warning'); return; }

  const keywords = rawKws.split('\n').map(k => k.trim()).filter(k => k.length > 0);
  if (!keywords.length) { showToast('No valid keywords found', 'warning'); return; }

  const total = keywords.length * countPerKw;
  setState('spinner');
  document.getElementById('spinner-msg').textContent =
    `Generating ${total} topics for ${keywords.length} keyword${keywords.length > 1 ? 's' : ''}…`;

  const btn = document.getElementById('generate-btn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Working…';

  fetch(BASE_URL + '/api/topics/seed-generate', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({ project_id: parseInt(projectId), page_type_id: parseInt(pageTypeId), keywords, count_per_keyword: countPerKw })
  })
  .then(r => r.json())
  .then(data => {
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-stars me-2"></i>Generate Topics';
    if (data.success && data.data && data.data.topics) {
      generatedTopics = data.data.topics;
      renderTable(generatedTopics);
      setState('table');
      showToast(generatedTopics.length + ' topics generated', 'success');
    } else {
      setState('empty');
      showToast(data.message || 'Generation failed', 'danger');
    }
  })
  .catch(err => {
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-stars me-2"></i>Generate Topics';
    setState('empty');
    showToast('Network error: ' + err.message, 'danger');
  });
}

function renderTable(topics) {
  const tbody = document.getElementById('topics-tbody');
  tbody.innerHTML = topics.map((t, i) => `
    <tr>
      <td><input type="checkbox" class="form-check-input topic-row-check" value="${i}" checked></td>
      <td class="fw-medium" style="font-size:13px;">${escH(t.title || '')}</td>
      <td><span class="badge bg-secondary-subtle text-secondary" style="font-size:11px;">${escH(t.primary_keyword || '')}</span></td>
      <td><span class="badge bg-info-subtle text-info" style="font-size:10px;">${escH(t.search_intent || 'informational')}</span></td>
      <td class="text-muted small">${escH((t.content_angle || '').substring(0, 80))}${(t.content_angle||'').length > 80 ? '…' : ''}</td>
    </tr>`).join('');

  document.getElementById('count-badge').textContent = topics.length + ' topics';
  document.getElementById('results-actions').style.display = '';
}

function selectAll(checked) {
  document.querySelectorAll('.topic-row-check').forEach(cb => cb.checked = checked);
}

function saveTopics() {
  const projectId  = document.getElementById('project-select').value;
  const pageTypeId = document.getElementById('pagetype-select').value;
  const checked    = [...document.querySelectorAll('.topic-row-check:checked')].map(cb => parseInt(cb.value));

  if (!checked.length) { showToast('Select at least one topic', 'warning'); return; }

  const toSave = checked.map(i => generatedTopics[i]);
  const btn    = document.getElementById('save-btn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Saving…';

  fetch(BASE_URL + '/api/topics/seed-save', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({ project_id: parseInt(projectId), page_type_id: parseInt(pageTypeId), topics: toSave })
  })
  .then(r => r.json())
  .then(data => {
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-floppy me-1"></i>Save Selected';
    if (data.success) {
      showToast(data.data.count + ' topics saved to your project!', 'success');
      setTimeout(() => window.location.href = BASE_URL + '/topics?project_id=' + projectId, 1200);
    } else {
      showToast(data.message || 'Save failed', 'danger');
    }
  })
  .catch(() => {
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-floppy me-1"></i>Save Selected';
    showToast('Network error', 'danger');
  });
}

function setState(state) {
  document.getElementById('empty-state').style.display   = state === 'empty'   ? '' : 'none';
  document.getElementById('spinner-state').style.display = state === 'spinner' ? '' : 'none';
  document.getElementById('table-state').style.display   = state === 'table'   ? '' : 'none';
}

function escH(s) {
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>
JS;
require __DIR__ . '/../layout/footer.php';
?>
