import {defineStore} from 'pinia';

export const useNews = defineStore('news', {
  state: () => ({
    articles: [] as {
      id: number,
      title: string,
      summary: string,
      url: string,
      published: number,
      country: string,
      created_at: number
    }[],
    lastSync: 0,
    clientTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    clientLocale: Intl.DateTimeFormat().resolvedOptions().locale,
    page: 1,
    pageSize: 12,
    hasMore: true,
    allArticles: [] as {
      id: number,
      title: string,
      summary: string,
      url: string,
      published: number,
      country: string,
      created_at: number
    }[],
    currentFilters: {} as Record<string, string | boolean>
  }),
  actions: {
    async loadLastSync() {
      const {ts} = await fetch('/meta/last-sync').then(r => r.json());
      this.lastSync = ts * 1000; // store ms
    },
    canManualSync() {
      return Date.now() - this.lastSync > 30 * 60 * 1000; // 30‑min guard
    },
    async sync(filters: Record<string, string | boolean> = {}) {
      if (!this.canManualSync()) {
        console.log('Too soon to sync again');
        return;
      }

      // Include timezone in the request
      const filtersWithTz = {
        ...filters,
        timezone: this.clientTimezone
      };
      const q = new URLSearchParams(filtersWithTz as Record<string, string>).toString();
      const res = await fetch(`/news?${q}`);

      if (res.ok) {
        const data = await res.json();
        this.allArticles = data;
        this.currentFilters = filters;
        this.page = 1;
        this.hasMore = data.length > this.pageSize;
        this.articles = data.slice(0, this.pageSize);
        this.lastSync = Date.now();
      }
    },
    async getNews(filters: Record<string, string | boolean> = {}) {
      try {
        const filtersWithTz = {
          ...filters,
          timezone: this.clientTimezone
        };
        const q = new URLSearchParams(filtersWithTz as Record<string, string>).toString();
        const res = await fetch(`/news?${q}`);

        if (!res.ok) {
          throw new Error(`HTTP ${res.status}: ${res.statusText}`);
        }

        const contentType = res.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
          throw new Error('Response is not JSON');
        }

        const data = await res.json();
        this.allArticles = data;
        this.currentFilters = filters;
        this.page = 1;
        this.hasMore = data.length > this.pageSize;
        this.articles = data.slice(0, this.pageSize);
        return data;
      } catch (error) {
        console.error('Failed to get news:', error);
        return [];
      }
    },

    async loadMore() {
      if (!this.hasMore) return;

      const nextPage = this.page + 1;
      const startIndex = this.page * this.pageSize;
      const endIndex = startIndex + this.pageSize;

      const nextPageItems = this.allArticles.slice(startIndex, endIndex);

      if (nextPageItems.length > 0) {
        this.articles = [...this.articles, ...nextPageItems];
        this.page = nextPage;
        this.hasMore = endIndex < this.allArticles.length;
      } else {
        this.hasMore = false;
      }
    },

    // Reset pagination state
    resetPagination() {
      this.page = 1;
      this.hasMore = this.allArticles.length > this.pageSize;
      this.articles = this.allArticles.slice(0, this.pageSize);
    },

    // New convenience methods
    async getAllNews() {
      return this.getNews({all_countries: 'true', all_dates: 'true'});
    },

    async getNewsForCountries(countries: string[], from?: string, to?: string) {
      const filters: Record<string, string> = {
        country: countries.join(',')
      };
      if (from) filters.from_ = from;
      if (to) filters.to_ = to;
      return this.getNews(filters);
    }
  }
});
