<ul class="nav ab-tabs mb-3">
  <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tabAssistant">AI Assistant</a></li>
  <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabChatbot">Chatbot</a></li>
  <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabVoice">Voice Agent</a></li>
</ul>

<div class="tab-content">
  <?php foreach (['ai_assistant' => 'tabAssistant', 'chatbot' => 'tabChatbot', 'voice_agent' => 'tabVoice'] as $feature => $tabId): ?>
  <div class="tab-pane fade <?= $feature==='ai_assistant'?'show active':'' ?>" id="<?= $tabId ?>">
    <div class="d-flex justify-content-end mb-3">
      <button class="btn btn-primary btn-sm ab-new-prompt" data-feature="<?= $feature ?>"><i class="bi bi-plus-lg me-1"></i>New Prompt</button>
    </div>
    <?php foreach ($grouped[$feature] as $p): ?>
    <div class="ab-card mb-3">
      <div class="ab-card-body">
        <div class="d-flex justify-content-between">
          <div><h3 class="fs-6 mb-0"><?= e($p['name']) ?></h3><span class="ab-cell-sub"><?= e($p['business_line_name'] ?? 'Both brands') ?></span></div>
          <div class="d-flex gap-2 align-items-start">
            <span class="ab-badge <?= $p['is_active']?'bg-success-soft':'bg-secondary-soft' ?>"><?= $p['is_active']?'Active':'Inactive' ?></span>
            <button class="btn btn-icon btn-light-soft btn-sm ab-edit-prompt" data-id="<?= (int) $p['id'] ?>" data-name="<?= e($p['name']) ?>" data-prompt="<?= e($p['system_prompt']) ?>" data-feature="<?= $feature ?>"><i class="bi bi-pencil"></i></button>
            <button class="btn btn-icon btn-light-soft btn-sm ab-delete-prompt" data-id="<?= (int) $p['id'] ?>"><i class="bi bi-trash text-danger"></i></button>
          </div>
        </div>
        <p class="small mt-2 mb-0"><?= e($p['system_prompt']) ?></p>
      </div>
    </div>
    <?php endforeach; ?>
    <?php if (empty($grouped[$feature])): ?><div class="ab-empty small py-3">No prompts yet for this feature.</div><?php endif; ?>
  </div>
  <?php endforeach; ?>
</div>

<div class="modal fade" id="abPromptModal" tabindex="-1"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title" id="abPromptModalTitle">New Prompt</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <form id="abPromptForm">
      <input type="hidden" name="id"><input type="hidden" name="feature" id="abPromptFeature">
      <div class="row g-3">
        <div class="col-md-8"><label class="form-label ab-req">Name</label><input class="form-control" name="name" required></div>
        <div class="col-md-4"><label class="form-label">Business Line</label><select class="form-select" name="business_line_id"><option value="">Both brands</option><?php foreach ($businessLines as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-12"><label class="form-label ab-req">System Prompt</label><textarea class="form-control" name="system_prompt" rows="6" required></textarea></div>
        <div class="col-12"><div class="form-check"><input class="form-check-input" type="checkbox" name="is_active" checked><label class="form-check-label">Active</label></div></div>
      </div>
    </form>
  </div>
  <div class="modal-footer"><button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="abPromptSaveBtn">Save</button></div>
</div></div></div>

<script>
document.querySelectorAll('.ab-new-prompt').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var form = document.getElementById('abPromptForm');
    form.reset(); form.id.value = ''; document.getElementById('abPromptFeature').value = btn.dataset.feature;
    document.getElementById('abPromptModalTitle').textContent = 'New Prompt';
    new bootstrap.Modal(document.getElementById('abPromptModal')).show();
  });
});

document.querySelectorAll('.ab-edit-prompt').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var form = document.getElementById('abPromptForm');
    form.id.value = btn.dataset.id; form.name.value = btn.dataset.name; form.system_prompt.value = btn.dataset.prompt;
    document.getElementById('abPromptFeature').value = btn.dataset.feature;
    document.getElementById('abPromptModalTitle').textContent = 'Edit Prompt';
    new bootstrap.Modal(document.getElementById('abPromptModal')).show();
  });
});

document.getElementById('abPromptSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abPromptForm');
  var id = form.id.value;
  var fd = new FormData(form);
  var data = Object.fromEntries(fd.entries());
  data.is_active = form.is_active.checked ? 1 : 0;
  var url = id ? '<?= base_url('ai-prompts') ?>/' + id : '<?= base_url('ai-prompts') ?>';

  abFetch(url, { method: id ? 'PATCH' : 'POST', body: data }).then(function (res) {
    abToast(res.message);
    bootstrap.Modal.getInstance(document.getElementById('abPromptModal')).hide();
    setTimeout(function () { window.location.reload(); }, 600);
  }).catch(function (err) {
    abShowFormErrors(form, err.errors);
    abToast(err.message || 'Save failed.', 'danger');
  });
});

document.querySelectorAll('.ab-delete-prompt').forEach(function (btn) {
  btn.addEventListener('click', function () {
    if (!confirm('Delete this prompt?')) return;
    abFetch('<?= base_url('ai-prompts') ?>/' + btn.dataset.id, { method: 'DELETE' })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
});
</script>
