/**
 * Linha do tempo — eventos do app (cadastro, foto, segurança).
 * - Fila local: offline / falha de rede (chave registropro_timeline_events).
 * - Servidor: employee_timeline_events (persiste após logout; consultável pelo RH).
 */
(function (global) {
  'use strict';

  var STORAGE_KEY = 'registropro_timeline_events';
  var MAX_ITEMS = 150;

  function safeParse(raw) {
    try {
      var a = JSON.parse(raw || '[]');
      return Array.isArray(a) ? a : [];
    } catch (e) {
      return [];
    }
  }

  function saveArr(arr) {
    try {
      if (global.localStorage) global.localStorage.setItem(STORAGE_KEY, JSON.stringify(arr));
    } catch (e) {}
  }

  function getToken() {
    try {
      return global.localStorage ? global.localStorage.getItem('auth_token') || '' : '';
    } catch (e) {
      return '';
    }
  }

  function postAppend(item) {
    if (typeof global.registroProGetTimelineEventAppendApiUrl !== 'function') {
      return Promise.resolve(false);
    }
    var url = global.registroProGetTimelineEventAppendApiUrl();
    if (!url) return Promise.resolve(false);
    var token = getToken();
    if (!token) return Promise.resolve(false);

    var body = {
      event_type: item.type || 'app',
      title: item.title,
      body: item.body || '',
      client_event_id: item.id,
      occurred_at: item.at || undefined,
      auth_token: token
    };

    return fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        Authorization: 'Bearer ' + token
      },
      body: JSON.stringify(body)
    })
      .then(function (res) {
        return res.json().catch(function () {
          return null;
        });
      })
      .then(function (json) {
        return !!(json && json.ok);
      })
      .catch(function () {
        return false;
      });
  }

  function removeFromStorageById(clientId) {
    var arr = safeParse(global.localStorage && global.localStorage.getItem(STORAGE_KEY));
    var next = arr.filter(function (x) {
      return x.id !== clientId;
    });
    saveArr(next);
  }

  /**
   * Envia para o servidor todos os eventos ainda na fila local (sem token não faz nada).
   * @returns {Promise<void>}
   */
  function registroProTimelineFlushPending() {
    var arr = safeParse(global.localStorage && global.localStorage.getItem(STORAGE_KEY));
    if (!arr.length) return Promise.resolve();

    var token = getToken();
    if (!token) return Promise.resolve();

    function processNext(i) {
      if (i >= arr.length) return Promise.resolve();
      var item = arr[i];
      if (!item || !item.id || !item.title) {
        return processNext(i + 1);
      }
      if (item.synced === true) {
        return processNext(i + 1);
      }
      return postAppend(item).then(function (ok) {
        if (ok) {
          removeFromStorageById(item.id);
        }
        return processNext(i + 1);
      });
    }

    return processNext(0);
  }

  /**
   * @param {{ type?: string, title: string, body?: string, at?: string }} evt
   */
  function registroProTimelineLog(evt) {
    if (!evt || !evt.title) return;
    var item = {
      id: 'local_' + Date.now() + '_' + Math.random().toString(36).slice(2, 9),
      type: evt.type || 'app',
      title: String(evt.title),
      body: evt.body != null ? String(evt.body) : '',
      at: evt.at || new Date().toISOString()
    };
    var arr = safeParse(global.localStorage && global.localStorage.getItem(STORAGE_KEY));
    arr.unshift(item);
    if (arr.length > MAX_ITEMS) arr = arr.slice(0, MAX_ITEMS);
    saveArr(arr);

    try {
      registroProTimelineFlushPending().catch(function () {});
    } catch (e2) {}
  }

  /**
   * Eventos ainda não sincronizados (fila local). Na tela, unir com GET do servidor.
   */
  function registroProTimelineGetLocal() {
    var arr = safeParse(global.localStorage && global.localStorage.getItem(STORAGE_KEY));
    return arr.filter(function (x) {
      return x && x.title && x.synced !== true;
    });
  }

  global.registroProTimelineLog = registroProTimelineLog;
  global.registroProTimelineGetLocal = registroProTimelineGetLocal;
  global.registroProTimelineFlushPending = registroProTimelineFlushPending;
})(typeof window !== 'undefined' ? window : this);
