// Shared data + primitives for both design options

// Fallback data (used while loading or if API fails)
const FALLBACK_CLINICS = [
  {
    id: 'c1',
    name: 'Nha Khoa Kim Phú Nhuận',
    district: 'Phú Nhuận',
    address: '123 Phan Đình Phùng, P.15',
    rating: 4.8,
    reviews: 1247,
    services: ['Niềng răng', 'Implant', 'Tẩy trắng', 'Bọc sứ'],
    price: 'Từ 500k',
    verified: true,
    years: 18,
    doctors: 12,
    hue: 210,
  },
  {
    id: 'c2',
    name: 'Peace Dentistry Phú Nhuận',
    district: 'Phú Nhuận',
    address: '88 Nguyễn Văn Trỗi, P.8',
    rating: 4.9,
    reviews: 892,
    services: ['Implant', 'Niềng Invisalign', 'Veneer'],
    price: 'Từ 800k',
    verified: true,
    years: 10,
    doctors: 8,
    hue: 180,
  },
  {
    id: 'c3',
    name: 'Nha Khoa Sài Gòn B.H',
    district: 'Phú Nhuận',
    address: '456 Hoàng Văn Thụ, P.4',
    rating: 4.7,
    reviews: 2103,
    services: ['Niềng răng', 'Nhổ răng khôn', 'Trám răng'],
    price: 'Từ 300k',
    verified: true,
    years: 22,
    doctors: 15,
    hue: 160,
  },
  {
    id: 'c4',
    name: 'Nha Khoa Paris Phú Nhuận',
    district: 'Phú Nhuận',
    address: '12 Nguyễn Kiệm, P.3',
    rating: 4.6,
    reviews: 1589,
    services: ['Niềng răng', 'Implant', 'Bọc răng sứ'],
    price: 'Từ 600k',
    verified: true,
    years: 15,
    doctors: 10,
    hue: 230,
  },
  {
    id: 'c5',
    name: 'Nha Khoa Việt Smile',
    district: 'Phú Nhuận',
    address: '77 Lê Văn Sỹ, P.13',
    rating: 4.5,
    reviews: 634,
    services: ['Niềng răng trẻ em', 'Tẩy trắng', 'Trám răng'],
    price: 'Từ 250k',
    verified: false,
    years: 7,
    doctors: 5,
    hue: 195,
  },
];

const FALLBACK_ARTICLES = [
  {
    id: 'a1',
    category: 'Niềng răng',
    title: 'Niềng răng mắc cài kim loại: Ưu điểm, nhược điểm & chi phí 2026',
    excerpt: 'Phương pháp niềng răng mắc cài kim loại vẫn là lựa chọn phổ biến nhất tại Việt Nam. Cùng tìm hiểu chi tiết về hiệu quả, thời gian và chi phí...',
    author: 'BS. Nguyễn Thị Minh',
    date: '18/04/2026',
    readTime: 8,
    views: '12.4k',
    featured: true,
  },
  {
    id: 'a2',
    category: 'Implant',
    title: 'Trồng răng Implant: Quy trình 5 bước chuẩn y khoa',
    excerpt: 'Implant nha khoa là giải pháp phục hình răng mất hiện đại nhất. Bài viết mô tả quy trình từ khám, cắm trụ đến gắn mão sứ...',
    author: 'BS. Trần Văn Hùng',
    date: '15/04/2026',
    readTime: 12,
    views: '8.9k',
  },
  {
    id: 'a3',
    category: 'Chăm sóc',
    title: '7 thói quen khiến răng vàng nhanh chóng bạn nên tránh',
    excerpt: 'Cà phê, trà, thuốc lá... có thực sự là nguyên nhân chính khiến răng xỉn màu? Nha sĩ chia sẻ sự thật ít người biết.',
    author: 'BS. Lê Hải Anh',
    date: '12/04/2026',
    readTime: 6,
    views: '24.1k',
  },
  {
    id: 'a4',
    category: 'Tẩy trắng',
    title: 'Tẩy trắng răng tại nhà: An toàn hay chỉ là quảng cáo?',
    excerpt: 'Các sản phẩm tẩy trắng tại nhà đang được quảng bá mạnh. Đâu là sự thật về độ an toàn và hiệu quả thực sự?',
    author: 'BS. Phạm Thu Hà',
    date: '10/04/2026',
    readTime: 7,
    views: '15.7k',
  },
  {
    id: 'a5',
    category: 'Trẻ em',
    title: 'Khi nào nên đưa trẻ đi khám răng lần đầu?',
    excerpt: 'Hiệp hội Nha khoa Hoa Kỳ khuyến cáo trẻ nên được khám răng từ khi mọc chiếc răng sữa đầu tiên...',
    author: 'BS. Đỗ Ngọc Lan',
    date: '08/04/2026',
    readTime: 5,
    views: '6.2k',
  },
  {
    id: 'a6',
    category: 'Răng khôn',
    title: 'Nhổ răng khôn: Khi nào cần, khi nào không?',
    excerpt: 'Không phải ai cũng cần nhổ răng khôn. Hướng dẫn chi tiết giúp bạn nhận biết dấu hiệu và quyết định đúng.',
    author: 'BS. Hoàng Minh Tuấn',
    date: '05/04/2026',
    readTime: 9,
    views: '18.3k',
  },
];

// Dynamic data store (populated from API)
let CLINICS = [...FALLBACK_CLINICS];
let ARTICLES = [...FALLBACK_ARTICLES];

const SERVICES = [
  { id: 's1', name: 'Niềng răng mắc cài', min: 25, max: 55, unit: 'triệu', duration: '18-24 tháng' },
  { id: 's2', name: 'Niềng Invisalign', min: 80, max: 150, unit: 'triệu', duration: '12-18 tháng' },
  { id: 's3', name: 'Cấy ghép Implant', min: 18, max: 45, unit: 'triệu/trụ', duration: '3-6 tháng' },
  { id: 's4', name: 'Bọc răng sứ', min: 2.5, max: 15, unit: 'triệu/răng', duration: '5-7 ngày' },
  { id: 's5', name: 'Tẩy trắng răng', min: 1.5, max: 5, unit: 'triệu', duration: '1-2 buổi' },
  { id: 's6', name: 'Trám răng thẩm mỹ', min: 0.3, max: 1.2, unit: 'triệu/răng', duration: '30 phút' },
];

const DISTRICTS = ['Tất cả', 'Phú Nhuận', 'Quận 1', 'Quận 3', 'Quận 10', 'Bình Thạnh', 'Tân Bình'];

const FAQS = [
  { q: 'Niềng răng có đau không?', a: 'Đau nhẹ trong 3-5 ngày đầu sau khi gắn mắc cài, sau đó quen dần. Mỗi lần siết dây cung cũng có thể gây ê nhẹ 1-2 ngày.' },
  { q: 'Implant có tồn tại suốt đời không?', a: 'Với chăm sóc tốt, trụ Implant titanium có thể dùng 20-30 năm hoặc lâu hơn. Phần mão sứ có thể cần thay sau 10-15 năm.' },
  { q: 'Tẩy trắng răng có hại men răng không?', a: 'Tẩy trắng đúng kỹ thuật tại phòng khám an toàn. Tuy nhiên không nên lạm dụng, khoảng cách tối thiểu giữa 2 lần là 6 tháng.' },
  { q: 'Trẻ em mấy tuổi nên niềng răng?', a: 'Thời điểm lý tưởng là 10-14 tuổi khi xương hàm còn phát triển. Tuy nhiên có thể can thiệp sớm từ 6-7 tuổi nếu có sai lệch nghiêm trọng.' },
];

// Placeholder "image" — a soft gradient square with a tiny tooth glyph label
function ImgPlaceholder({ hue = 210, sat = 30, label, height = '100%', radius = 0, style = {}, light = false }) {
  const bg1 = `oklch(${light ? 0.92 : 0.88} ${sat / 200} ${hue})`;
  const bg2 = `oklch(${light ? 0.96 : 0.94} ${sat / 300} ${hue + 20})`;
  return (
    <div style={{
      width: '100%', height, borderRadius: radius,
      background: `linear-gradient(135deg, ${bg1}, ${bg2})`,
      position: 'relative', overflow: 'hidden',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      ...style,
    }}>
      {/* subtle stripes */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `repeating-linear-gradient(45deg, transparent 0 8px, rgba(255,255,255,.12) 8px 9px)`,
        pointerEvents: 'none',
      }} />
      {label && (
        <div style={{
          position: 'relative', zIndex: 1,
          fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
          fontSize: 9, letterSpacing: 0.6,
          color: `oklch(0.35 0.03 ${hue})`, opacity: 0.7,
          textTransform: 'uppercase', padding: '3px 8px',
          background: 'rgba(255,255,255,.4)', borderRadius: 2,
        }}>{label}</div>
      )}
    </div>
  );
}

// Tiny tooth SVG logo mark
function ToothMark({ size = 20, color = 'currentColor' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M7.5 3C5.5 3 4 4.5 4 7c0 3 1 5 1.5 9 .3 2.3.7 4 2 4 1.2 0 1.5-1.5 2-4 .2-1 .5-1.5 1-1.5h3c.5 0 .8.5 1 1.5.5 2.5.8 4 2 4 1.3 0 1.7-1.7 2-4 .5-4 1.5-6 1.5-9 0-2.5-1.5-4-3.5-4-1.2 0-2 .5-2.8 1C13 4.4 12.5 4.5 12 4.5s-1-.1-1.7-.5C9.5 3.5 8.7 3 7.5 3Z"/>
    </svg>
  );
}

function StarRow({ rating, size = 12, color = '#f5b301', trackColor = 'rgba(0,0,0,.1)' }) {
  const full = Math.floor(rating);
  const half = rating - full >= 0.5;
  return (
    <span style={{ display: 'inline-flex', gap: 1, color }}>
      {[0,1,2,3,4].map(i => (
        <svg key={i} width={size} height={size} viewBox="0 0 16 16" fill={i < full ? color : (i === full && half ? `url(#half${i}${rating})` : trackColor)}>
          {i === full && half && (
            <defs>
              <linearGradient id={`half${i}${rating}`}>
                <stop offset="50%" stopColor={color}/>
                <stop offset="50%" stopColor={trackColor}/>
              </linearGradient>
            </defs>
          )}
          <path d="M8 1.5l2.1 4.2 4.6.7-3.3 3.2.8 4.6L8 11.9l-4.2 2.3.8-4.6L1.3 6.4l4.6-.7L8 1.5z"/>
        </svg>
      ))}
    </span>
  );
}

// Icon set (stroke-only, consistent)
const Icon = {
  Search: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>,
  MapPin: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 10c0 6-8 13-8 13s-8-7-8-13a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/></svg>,
  Clock: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>,
  Phone: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92Z"/></svg>,
  Calendar: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>,
  Shield: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/><path d="m9 12 2 2 4-4"/></svg>,
  Check: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>,
  Star: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3.1 6.3 7 1-5 4.9 1.2 6.8L12 18l-6.3 3 1.2-6.8-5-4.9 7-1L12 2z"/></svg>,
  Arrow: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  ChevronRight: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6"/></svg>,
  ChevronDown: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m6 9 6 6 6-6"/></svg>,
  Menu: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>,
  Heart: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78Z"/></svg>,
  Filter: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/></svg>,
  User: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
  Book: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>,
  Eye: (p) => <svg {...p} width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>,
};

// Load data from API on startup
async function loadDataFromAPI() {
  try {
    const [clinicsRes, articlesRes] = await Promise.all([
      fetch('/api/clinics?status=approved').then(r => r.json()),
      fetch('/api/articles?status=published').then(r => r.json())
    ]);

    if (clinicsRes.success && clinicsRes.data.length > 0) {
      CLINICS.length = 0;
      clinicsRes.data.forEach(c => {
        CLINICS.push({
          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,
          hue: Math.abs(c.name.charCodeAt(0) * 7) % 360,
        });
      });
    }

    if (articlesRes.success && articlesRes.data.length > 0) {
      ARTICLES.length = 0;
      articlesRes.data.forEach(a => {
        ARTICLES.push({
          id: a.id,
          category: a.category,
          title: a.title,
          slug: a.slug,
          excerpt: a.body ? a.body.substring(0, 150) + '...' : 'Đang cập nhật nội dung...',
          author: a.author_id || 'Biên tập viên',
          date: a.published_at || a.updated_at,
          readTime: a.read_time || 5,
          views: a.views >= 1000 ? `${(a.views / 1000).toFixed(1)}k` : String(a.views || 0),
          featured: a.ranking === 1,
        });
      });
    }

    console.log('Data loaded from API:', { clinics: CLINICS.length, articles: ARTICLES.length });
  } catch (err) {
    console.warn('API unavailable, using fallback data:', err.message);
  }
}

// Auto-load data when script runs
loadDataFromAPI();

Object.assign(window, {
  CLINICS, ARTICLES, SERVICES, DISTRICTS, FAQS,
  FALLBACK_CLINICS, FALLBACK_ARTICLES,
  ImgPlaceholder, ToothMark, StarRow, Icon,
  loadDataFromAPI,
});
