// Közös segédek: API-hívás, formázás, # alapú útválasztó, bejelentkezett felhasználó, adatbetöltés.
// Minden fájl egy függvénybe van csomagolva, hogy a helyi nevek ne ütközzenek egymással;
// amit más fájlnak is látnia kell, azt a végén a window objektumra tesszük.
(() => {
  const { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } = React;

  // ---------- API ----------

  class ApiError extends Error {
    constructor(status, message, fields) {
      super(message);
      this.status = status;
      this.fields = fields ?? {};
    }
  }

  // Ezeknél a 401 várható válasz (nincs belépve), nem jelent lejárt munkamenetet.
  const QUIET_401 = ['/auth/me', '/auth/login', '/auth/register'];

  async function request(method, path, { body, raw, type } = {}) {
    const headers = {};
    let payload;
    if (raw !== undefined) {
      headers['Content-Type'] = type;
      payload = raw;
    } else if (body !== undefined) {
      headers['Content-Type'] = 'application/json';
      payload = JSON.stringify(body);
    }

    let response;
    try {
      response = await fetch(`/api${path}`, { method, headers, body: payload, credentials: 'same-origin' });
    } catch {
      throw new ApiError(0, 'A szerver nem érhető el. Próbáld újra később.');
    }

    const data = await response.json().catch(() => null);
    if (!response.ok) {
      if (response.status === 401 && !QUIET_401.includes(path)) {
        window.dispatchEvent(new Event('session-expired'));
      }
      throw new ApiError(response.status, data?.message ?? 'Hiba történt.', data?.errors);
    }
    return data;
  }

  const api = {
    get: (path) => request('GET', path),
    post: (path, body) => request('POST', path, { body }),
    put: (path, body) => request('PUT', path, { body }),
    delete: (path) => request('DELETE', path),
    upload: (path, file) => request('POST', path, { raw: file, type: file.type }),
  };

  // ---------- Formázás (magyar) ----------

  const numberFormat = new Intl.NumberFormat('hu-HU');
  const dateTimeFormat = new Intl.DateTimeFormat('hu-HU', {
    year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
  });
  const dateFormat = new Intl.DateTimeFormat('hu-HU', { year: 'numeric', month: 'short', day: 'numeric' });

  const formatHuf = (amount) => `${numberFormat.format(amount)} Ft`;
  const formatDateTime = (value) => dateTimeFormat.format(new Date(value));
  const formatDate = (value) => dateFormat.format(new Date(value));
  const formatDistance = (km) => `${new Intl.NumberFormat('hu-HU', { maximumFractionDigits: 1 }).format(km)} km`;

  const STATUS_LABELS = {
    NEW: 'Új', QUOTED: 'Van ajánlat', ACCEPTED: 'Elfogadva', IN_PROGRESS: 'Folyamatban',
    COMPLETED: 'Kész', REVIEWED: 'Értékelve', CANCELLED: 'Lemondva',
  };
  const STATUS_COLORS = {
    NEW: 'blue', QUOTED: 'amber', ACCEPTED: 'indigo', IN_PROGRESS: 'purple',
    COMPLETED: 'green', REVIEWED: 'green', CANCELLED: 'gray',
  };
  const QUOTE_STATUS_LABELS = { PENDING: 'Függőben', ACCEPTED: 'Elfogadva', REJECTED: 'Elutasítva', WITHDRAWN: 'Visszavonva' };
  const QUOTE_STATUS_COLORS = { PENDING: 'amber', ACCEPTED: 'green', REJECTED: 'gray', WITHDRAWN: 'gray' };
  const URGENCY_LABELS = { EMERGENCY: 'Sürgős (azonnal)', WITHIN_24H: '24 órán belül', FLEXIBLE: 'Rugalmas' };
  const URGENCY_SHORT = { EMERGENCY: 'Sürgős', WITHIN_24H: '24 órán belül', FLEXIBLE: 'Rugalmas' };
  const ROLE_HOME = { CUSTOMER: '/customer', ELECTRICIAN: '/electrician', ADMIN: '/admin' };
  const homePathFor = (role) => ROLE_HOME[role] ?? '/';

  // ---------- Útválasztó: az oldalcím a # után van (pl. /#/customer/jobs/3) ----------

  const currentHash = () => window.location.hash.replace(/^#/, '') || '/';
  const currentPath = () => currentHash().split('?')[0];

  function navigate(to, { replace = false } = {}) {
    if (replace) {
      window.location.replace(`#${to}`);
    } else {
      window.location.hash = to;
    }
  }

  /** "/customer/jobs/:id" mintát illeszt az útvonalra; { id: '3' } vagy null. */
  function matchPath(pattern, path) {
    const patternParts = pattern.split('/').filter(Boolean);
    const pathParts = path.split('/').filter(Boolean);
    if (patternParts.length !== pathParts.length) {
      return null;
    }
    const params = {};
    for (let i = 0; i < patternParts.length; i += 1) {
      if (patternParts[i].startsWith(':')) {
        params[patternParts[i].slice(1)] = decodeURIComponent(pathParts[i]);
      } else if (patternParts[i] !== pathParts[i]) {
        return null;
      }
    }
    return params;
  }

  function useHashPath() {
    const [path, setPath] = useState(currentPath());
    useEffect(() => {
      const update = () => {
        setPath(currentPath());
        window.scrollTo(0, 0);
      };
      window.addEventListener('hashchange', update);
      return () => window.removeEventListener('hashchange', update);
    }, []);
    return path;
  }

  const RouteContext = createContext({ params: {} });
  const useParams = () => useContext(RouteContext).params;

  /** A # utáni kérdőjeles rész: /#/register?role=ELECTRICIAN */
  function useQueryParams() {
    useContext(RouteContext); // az útvonalváltásnál újraszámolja
    return new URLSearchParams(currentHash().split('?')[1] ?? '');
  }

  function Link({ to, children, className = '', ...rest }) {
    return (
      <a href={`#${to}`} className={className} {...rest}>
        {children}
      </a>
    );
  }

  // ---------- Bejelentkezett felhasználó ----------

  const AuthContext = createContext(null);

  function AuthProvider({ children }) {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);

    const refresh = useCallback(async () => {
      try {
        const { user: current } = await api.get('/auth/me');
        setUser(current);
        return current;
      } catch {
        setUser(null);
        return null;
      }
    }, []);

    // Induláskor: ha van érvényes süti, a szerver megadja a felhasználót.
    useEffect(() => {
      refresh().finally(() => setLoading(false));
    }, [refresh]);

    useEffect(() => {
      const expired = () => setUser(null);
      window.addEventListener('session-expired', expired);
      return () => window.removeEventListener('session-expired', expired);
    }, []);

    const value = useMemo(
      () => ({
        user,
        loading,
        refresh,
        async login(credentials) {
          const { user: loggedIn } = await api.post('/auth/login', credentials);
          setUser(loggedIn);
          return loggedIn;
        },
        async register(details) {
          const { user: created } = await api.post('/auth/register', details);
          setUser(created);
          return created;
        },
        async logout() {
          try {
            await api.post('/auth/logout');
          } finally {
            setUser(null);
          }
        },
      }),
      [user, loading, refresh],
    );

    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
  }

  const useAuth = () => useContext(AuthContext);

  // ---------- Adatbetöltés useEffect-ben ----------

  /** Visszaadja: { data, error, loading, reload }. A `deps` szabályozza, mikor töltsön újra. */
  function useLoad(loader, deps = []) {
    const [state, setState] = useState({ data: null, error: null, loading: true });
    const requestId = useRef(0);

    const load = useCallback(async () => {
      const current = ++requestId.current;
      try {
        const data = await loader();
        if (current === requestId.current) setState({ data, error: null, loading: false });
      } catch (error) {
        if (current === requestId.current) setState({ data: null, error: error.message, loading: false });
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, deps);

    useEffect(() => {
      load();
      return () => {
        requestId.current += 1;
      };
    }, [load]);

    return { ...state, reload: load };
  }

  Object.assign(window, {
    api, ApiError,
    formatHuf, formatDateTime, formatDate, formatDistance,
    STATUS_LABELS, STATUS_COLORS, QUOTE_STATUS_LABELS, QUOTE_STATUS_COLORS,
    URGENCY_LABELS, URGENCY_SHORT, homePathFor,
    navigate, matchPath, useHashPath, RouteContext, useParams, useQueryParams, Link,
    AuthProvider, useAuth, useLoad,
  });
})();
