// API Client for D1 Database

const API_BASE = '/api';

async function fetchAPI(endpoint, options = {}) {
  try {
    const res = await fetch(`${API_BASE}${endpoint}`, {
      headers: { 'Content-Type': 'application/json' },
      ...options,
    });
    const data = await res.json();
    if (!data.success) throw new Error(data.error || 'API Error');
    return data.data;
  } catch (err) {
    console.error(`API Error [${endpoint}]:`, err);
    throw err;
  }
}

const API = {
  articles: {
    list: (params = {}) => {
      const query = new URLSearchParams(params).toString();
      return fetchAPI(`/articles${query ? `?${query}` : ''}`);
    },
    get: (id) => fetchAPI(`/articles/${id}`),
    create: (data) => fetchAPI('/articles', { method: 'POST', body: JSON.stringify(data) }),
    update: (id, data) => fetchAPI(`/articles/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id) => fetchAPI(`/articles/${id}`, { method: 'DELETE' }),
  },

  clinics: {
    list: (params = {}) => {
      const query = new URLSearchParams(params).toString();
      return fetchAPI(`/clinics${query ? `?${query}` : ''}`);
    },
    get: (id) => fetchAPI(`/clinics/${id}`),
    create: (data) => fetchAPI('/clinics', { method: 'POST', body: JSON.stringify(data) }),
    update: (id, data) => fetchAPI(`/clinics/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  },

  bookings: {
    list: (params = {}) => {
      const query = new URLSearchParams(params).toString();
      return fetchAPI(`/bookings${query ? `?${query}` : ''}`);
    },
    get: (id) => fetchAPI(`/bookings/${id}`),
    create: (data) => fetchAPI('/bookings', { method: 'POST', body: JSON.stringify(data) }),
    updateStatus: (id, status) => fetchAPI(`/bookings/${id}`, { method: 'PUT', body: JSON.stringify({ status }) }),
  },

  reviews: {
    list: (params = {}) => {
      const query = new URLSearchParams(params).toString();
      return fetchAPI(`/reviews${query ? `?${query}` : ''}`);
    },
    create: (data) => fetchAPI('/reviews', { method: 'POST', body: JSON.stringify(data) }),
  },

  users: {
    list: (params = {}) => {
      const query = new URLSearchParams(params).toString();
      return fetchAPI(`/users${query ? `?${query}` : ''}`);
    },
  },

  categories: {
    list: () => fetchAPI('/categories'),
  },

  keywords: {
    list: () => fetchAPI('/keywords'),
  },

  stats: {
    get: () => fetchAPI('/stats'),
  },
};

// React hook for data fetching
function useAPI(fetcher, deps = []) {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    let mounted = true;
    setLoading(true);
    fetcher()
      .then(result => mounted && setData(result))
      .catch(err => mounted && setError(err))
      .finally(() => mounted && setLoading(false));
    return () => { mounted = false; };
  }, deps);

  return { data, loading, error, refetch: () => fetcher().then(setData) };
}

// Transform DB clinic to frontend format
function transformClinic(c) {
  return {
    id: c.id,
    name: c.name,
    district: c.district,
    address: `${c.district}, ${c.city}`,
    rating: c.rating || 0,
    reviews: c.reviews_count || 0,
    services: c.services ? c.services.split(',') : [],
    price: c.price_range || 'Liên hệ',
    verified: !!c.verified,
    phone: c.phone,
    city: c.city,
    status: c.status,
    hue: Math.abs(c.name.charCodeAt(0) * 7) % 360,
  };
}

// Transform DB article to frontend format
function transformArticle(a) {
  return {
    id: a.id,
    category: a.category,
    title: a.title,
    slug: a.slug,
    excerpt: a.body ? a.body.substring(0, 150) + '...' : '',
    author: a.author_id,
    date: a.published_at || a.updated_at,
    readTime: a.read_time || 5,
    views: a.views >= 1000 ? `${(a.views / 1000).toFixed(1)}k` : a.views,
    featured: a.ranking === 1,
    status: a.status,
    seoScore: a.seo_score,
    focusKw: a.focus_kw,
  };
}

Object.assign(window, { API, useAPI, transformClinic, transformArticle });
