/**
 * سودانا — Global App Engine v22
 * Handles: API calls, tab switching, event tracking, error handling
 */
(function () {
  'use strict';

  const BASE = '/s26';
  const API  = BASE + '/api';

  // ── Core API call ─────────────────────────────────────────────
  window.SudannaAPI = {

    ask: async function (question, onChunk) {
      try {
        const r = await fetch(API + '/visitor_ask.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({ question })
        });
        const d = await r.json();
        if (typeof onChunk === 'function') onChunk(d);
        return d;
      } catch (e) {
        const err = { success: false, error: 'network', answer: 'تعذّر الاتصال. تحقق من الإنترنت.' };
        if (typeof onChunk === 'function') onChunk(err);
        return err;
      }
    },

    startFlow: async function (flowId, context) {
      try {
        const r = await fetch(API + '/flow/start.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({ flow_id: flowId, context: context || {} })
        });
        return await r.json();
      } catch (e) {
        return { error: 'network' };
      }
    },

    nextStep: async function (sessionId, input) {
      try {
        const r = await fetch(API + '/flow/next.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({ session_id: sessionId, input: input || {} })
        });
        return await r.json();
      } catch (e) {
        return { error: 'network' };
      }
    },

    runAgent: async function (apiKey, agentId, input) {
      try {
        const r = await fetch(API + '/engine/run.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + apiKey
          },
          body: JSON.stringify({ agent_id: agentId, input: input })
        });
        return await r.json();
      } catch (e) {
        return { error: 'network' };
      }
    },

    chat: async function (apiKey, message) {
      try {
        const r = await fetch(API + '/engine/chat.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + apiKey
          },
          body: JSON.stringify({ message: message })
        });
        return await r.json();
      } catch (e) {
        return { error: 'network' };
      }
    },

    track: function (event, meta) {
      fetch(API + '/hub/track.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ event: event, meta: meta || {} }),
        keepalive: true
      }).catch(function () {});
    }
  };

  // ── Tab switching ─────────────────────────────────────────────
  window.showTab = function (tabId, btn) {
    document.querySelectorAll('.tab-content').forEach(function (t) {
      t.style.display = 'none';
    });
    document.querySelectorAll('.tab-btn').forEach(function (b) {
      b.classList.remove('active');
    });
    var el = document.getElementById(tabId);
    if (el) el.style.display = 'block';
    if (btn) btn.classList.add('active');
  };

  // ── Service flow triggers ─────────────────────────────────────
  window.triggerService = function (service) {
    var flowMap = {
      medical:     'medical_telemedicine_v1',
      legal:       'legal_consultation_v1',
      business:    'business_consulting_v1',
      engineering: 'engineering_consulting_v1',
      agriculture: 'agriculture_consulting_v1'
    };
    var flowId = flowMap[service];
    if (flowId) {
      SudannaAPI.track('service.click', { service: service });
      window.location.href = BASE + '/?service=' + service;
    } else {
      SudannaAPI.ask('أحتاج مساعدة في ' + service);
    }
  };

  // ── Global error handler ──────────────────────────────────────
  window.addEventListener('unhandledrejection', function (e) {
    console.warn('[Sudanna] Unhandled promise:', e.reason);
  });

  // ── Auto-track page view ──────────────────────────────────────
  SudannaAPI.track('hub.visit', {
    page: location.pathname,
    referrer: document.referrer
  });

})();
