// Platform definitions
const PLATFORMS = {
  didi_food: { id: "didi_food", label: "DiDi Food", color: "#E08C2F", short: "DIDI"  },
  rappi:     { id: "rappi",     label: "Rappi",     color: "#C2474B", short: "RAPPI" },
  uber_eats: { id: "uber_eats", label: "Uber Eats", color: "#3F7A56", short: "UBER"  },
};

// Map API status -> internal column
const STATUS_MAP = {
  received:   "new",
  accepted:   "progress",
  preparing:  "progress",
  ready:      "ready",
  picked_up:  "dispatched",
  delivered:  "done",
  cancelled:  "done",
  rejected:   "done",
};

const COLUMNS = [
  { id: "new",      title: "Nuevos pedidos", color: "var(--col-new)",      subLabel: "PENDIENTE" },
  { id: "progress", title: "En proceso",     color: "var(--col-progress)", subLabel: "EN COCINA" },
  { id: "ready",    title: "Para entregar",  color: "var(--col-ready)",    subLabel: "LISTO" },
];

const STATUS_FLOW = {
  new:        { next: "progress",   apiAction: "accept",     action: "Aceptar",              actionIcon: "check", color: "var(--accent)" },
  progress:   { next: "ready",      apiAction: "ready",      action: "Marcar como Listo",    actionIcon: "check", color: "var(--col-ready)" },
  ready:      { next: "dispatched", apiAction: "picked-up",  action: "Fuera para entrega",   actionIcon: "moto",  color: "#0EA37A" },
  dispatched: { next: "done",       apiAction: "delivered",  action: "Finalizar: Entregado", actionIcon: "check", color: "#477327" },
};

const PAYMENT = {
  card:           { label: "Tarjeta",  icon: "card",  color: "#2D5BD9" },
  cash:           { label: "Efectivo", icon: "money", color: "#477327" },
  digital_wallet: { label: "Wallet",   icon: "card",  color: "#7C3AED" },
  other:          { label: "Otro",     icon: "card",  color: "#6B7280" },
};

// Roles
const ROLES = {
  admin:   { label: "Administrador", icon: "shield" },
  gerente: { label: "Gerente",       icon: "user" },
  kds:     { label: "KDS",           icon: "chef" },
};

const ROLE_DEFAULT_VIEW = {
  admin:   "orders",
  gerente: "orders",
  kds:     "kds",
};

const SIDEBAR_BY_ROLE = {
  admin:   ["orders", "kds", "history", "reports", "menu", "storeconfig", "admin"],
  gerente: ["orders", "kds", "history", "reports", "storeconfig"],
  kds:     ["kds"],
};

// API base URL (same origin)
const API_BASE = "/api/v1";

// Auth helpers
function getToken() {
  return localStorage.getItem("deliveryToken");
}

function getUser() {
  try { return JSON.parse(localStorage.getItem("deliveryUser") || "null"); } catch { return null; }
}

function setAuth(token, user) {
  localStorage.setItem("deliveryToken", token);
  localStorage.setItem("deliveryUser", JSON.stringify(user));
}

function clearAuth() {
  localStorage.removeItem("deliveryToken");
  localStorage.removeItem("deliveryUser");
}

async function fetchWithAuth(url, opts = {}) {
  const token = getToken();
  const headers = { ...(opts.headers || {}), "Content-Type": "application/json" };
  if (token) headers["Authorization"] = `Bearer ${token}`;
  const res = await fetch(url, { ...opts, headers });
  if (res.status === 401) {
    clearAuth();
    // Notificar a App para que limpie el state de user sin parpadeo
    window.dispatchEvent(new Event("auth:logout"));
    window.location.hash = "#/login";
    throw new Error("Session expired");
  }
  return res;
}

// ============ SSE (Server-Sent Events) ============
function useSSE(onEvent) {
  const onEventRef = React.useRef(onEvent);
  onEventRef.current = onEvent;

  React.useEffect(() => {
    const token = getToken();
    if (!token) return;

    const url = `${API_BASE}/events`;
    // EventSource no soporta headers custom, usamos fetch + ReadableStream
    // AbortController garantiza que la conexión se cierre al desmontar el componente
    const controller = new AbortController();

    async function connect() {
      try {
        const response = await fetch(url, {
          headers: { Authorization: `Bearer ${token}`, Accept: "text/event-stream" },
          signal: controller.signal,
        });

        if (!response.ok || !response.body) return;

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";

        try {
          while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split("\n");
            buffer = lines.pop() || "";

            let eventType = null;
            let eventData = null;

            for (const line of lines) {
              if (line.startsWith("event: ")) {
                eventType = line.slice(7).trim();
              } else if (line.startsWith("data: ")) {
                eventData = line.slice(6).trim();
              } else if (line === "" && eventType && eventData) {
                try {
                  const parsed = JSON.parse(eventData);
                  if (eventType !== "ping" && eventType !== "connected") {
                    onEventRef.current(eventType, parsed);
                  }
                } catch { /* ignore parse errors */ }
                eventType = null;
                eventData = null;
              }
            }
          }
        } finally {
          reader.releaseLock();
        }
      } catch (err) {
        // AbortError es normal al desmontar — no reintentar
        if (err.name === "AbortError") return;
        if (!controller.signal.aborted) {
          console.warn("SSE connection error, will retry in 5s:", err.message);
          setTimeout(() => { if (!controller.signal.aborted) connect(); }, 5000);
        }
      }
    }

    connect();

    return () => { controller.abort(); };
  }, []);
}

Object.assign(window, {
  PLATFORMS, COLUMNS, STATUS_FLOW, STATUS_MAP, PAYMENT, API_BASE,
  ROLES, ROLE_DEFAULT_VIEW, SIDEBAR_BY_ROLE,
  getToken, getUser, setAuth, clearAuth, fetchWithAuth, useSSE,
});
