/**
 * Smart Dermatology – API client for Django backend
 * When the site is served from the same origin (e.g. Django), API calls use relative /api/.
 * Set window.API_BASE to override (e.g. 'http://127.0.0.1:8000' when opening HTML from file).
 */
(function () {
  var origin = typeof location !== 'undefined' && location.origin && location.origin !== 'null' && location.origin !== 'file://';
  window.API_BASE = window.API_BASE !== undefined ? window.API_BASE : (origin ? '' : 'http://127.0.0.1:8000');

  function getToken() {
    return localStorage.getItem('smart_derm_access') || sessionStorage.getItem('smart_derm_access');
  }

  function getHeaders(useFormData) {
    const headers = {};
    if (!useFormData) headers['Content-Type'] = 'application/json';
    const token = getToken();
    if (token) headers['Authorization'] = 'Bearer ' + token;
    return headers;
  }

  window.SmartDermAPI = {
    get baseUrl() { return window.API_BASE; },
    getToken: getToken,
    setToken: function (access, refresh, remember) {
      const storage = remember ? localStorage : sessionStorage;
      storage.setItem('smart_derm_access', access);
      if (refresh) storage.setItem('smart_derm_refresh', refresh);
    },
    clearAuth: function () {
      localStorage.removeItem('smart_derm_access');
      localStorage.removeItem('smart_derm_refresh');
      sessionStorage.removeItem('smart_derm_access');
      sessionStorage.removeItem('smart_derm_refresh');
    },

    auth: {
      register: function (data) {
        return fetch(API_BASE + '/api/auth/register/', {
          method: 'POST',
          headers: getHeaders(),
          body: JSON.stringify({
            email: data.email,
            password: data.password,
            full_name: data.full_name,
            username: data.email
          })
        }).then(function (r) {
          if (!r.ok) return r.json().then(function (j) { throw j; });
          return r.json();
        });
      },
      login: function (data, remember) {
        return fetch(API_BASE + '/api/auth/login/', {
          method: 'POST',
          headers: getHeaders(),
          body: JSON.stringify({ email: data.email, password: data.password })
        }).then(function (r) {
          if (!r.ok) return r.json().then(function (j) { throw j; });
          return r.json();
        }).then(function (res) {
          if (res.tokens) {
            SmartDermAPI.setToken(res.tokens.access, res.tokens.refresh, remember);
          }
          return res;
        });
      },
      me: function () {
        return fetch(API_BASE + '/api/auth/me/', { headers: getHeaders() }).then(function (r) {
          if (!r.ok) throw new Error('Not authenticated');
          return r.json();
        });
      }
    },

    skin: {
      analyze: function (imageFile) {
        var form = new FormData();
        form.append('image', imageFile);
        return fetch(API_BASE + '/api/skin/analyze/', {
          method: 'POST',
          headers: { 'Authorization': getToken() ? 'Bearer ' + getToken() : '' },
          body: form
        }).then(function (r) {
          if (!r.ok) return r.json().then(function (j) { throw j; });
          return r.json();
        });
      }
    },

    inquiries: {
      submit: function (data) {
        return fetch(API_BASE + '/api/inquiries/submit/', {
          method: 'POST',
          headers: getHeaders(),
          body: JSON.stringify({
            full_name: data.full_name,
            email: data.email,
            phone: data.phone || '',
            message: data.message
          })
        }).then(function (r) {
          if (!r.ok) return r.json().then(function (j) { throw j; });
          return r.json();
        });
      },
      list: function () {
        return fetch(API_BASE + '/api/inquiries/', { headers: getHeaders() }).then(function (r) {
          if (!r.ok) throw new Error('Failed to load');
          return r.json();
        });
      },
      markRead: function (id) {
        return fetch(API_BASE + '/api/inquiries/' + id + '/mark-read/', {
          method: 'PATCH',
          headers: getHeaders()
        }).then(function (r) {
          if (!r.ok) throw new Error('Failed');
          return r.json();
        });
      },
      reply: function (id, replyText) {
        return fetch(API_BASE + '/api/inquiries/' + id + '/reply/', {
          method: 'POST',
          headers: getHeaders(),
          body: JSON.stringify({ reply_text: replyText })
        }).then(function (r) {
          if (!r.ok) throw new Error('Failed');
          return r.json();
        });
      },
      delete: function (id) {
        return fetch(API_BASE + '/api/inquiries/' + id + '/', {
          method: 'DELETE',
          headers: getHeaders()
        }).then(function (r) {
          if (!r.ok) throw new Error('Failed');
        });
      }
    },

    admin: {
      dashboard: function () {
        return fetch(API_BASE + '/api/auth/admin/dashboard/', { headers: getHeaders() }).then(function (r) {
          if (!r.ok) throw new Error('Not authorized');
          return r.json();
        });
      },
      users: function (search) {
        var url = API_BASE + '/api/auth/admin/users/';
        if (search) url += '?search=' + encodeURIComponent(search);
        return fetch(url, { headers: getHeaders() }).then(function (r) {
          if (!r.ok) throw new Error('Not authorized');
          return r.json();
        });
      }
    }
  };
})();
