// ─────────────────────────────────────────────────────────────────────────
// IDIS — İşitme Merkezi SEO Dashboard
// Dynamic data: GSC + GA4 (live via /api/dashboard?range=...)
// Static (weekly refresh): COMPETITORS, KEYWORD_OVERLAP (Semrush TR DB)
// Illüstrasyon: BACKLINKS, TECH, AI_MENTIONS (entegrasyon sonraki fazda)
// ─────────────────────────────────────────────────────────────────────────

const BRANDS = [
  { id: "idis",    name: "IDIS",       url: "idis.com.tr",       initials: "ID", color: "#0E4F8A", logoTile: "id",  logoName: "is" },
  { id: "maxtone", name: "Maxtone",    url: "maxtone.com.tr",    initials: "MT", color: "#A06B2B" },
  { id: "emy",     name: "Emy İşitme", url: "emyisitme.com.tr",  initials: "EM", color: "#1F7A45" },
  { id: "siser",   name: "Siser",      url: "siser.com.tr",      initials: "SS", color: "#B5532E" },
  { id: "duymer",  name: "Duymer",     url: "duymer.com.tr",     initials: "DM", color: "#6B4FA0" },
];

// ─── Static (Semrush TR DB, Nisan 2026 — haftalık manuel refresh) ────────
const COMPETITORS = [
  { name: "IDIS",       clicks: 14292, kw: 1872, dr: 38, share: 19.6, you: true },
  { name: "Maxtone",    clicks: 25250, kw: 3601, dr: 51, share: 34.7 },
  { name: "Emy İşitme", clicks: 19298, kw: 3810, dr: 46, share: 26.5 },
  { name: "Siser",      clicks: 10040, kw: 2915, dr: 42, share: 13.8 },
  { name: "Duymer",     clicks:  3920, kw: 1240, dr: 35, share:  5.4 },
];

const KEYWORD_OVERLAP = [
  { kw: "kulak çınlaması",        vol: 40500, pos: [0, 0,  95, 0,  13] },
  { kw: "işitme cihazı",          vol: 33100, pos: [0, 2,  4,  8,  7]  },
  { kw: "kulak çınlaması neden olur", vol: 33100, pos: [0, 0, 0, 0, 9] },
  { kw: "işitme cihazı fiyatları",vol: 22200, pos: [0, 1,  2,  8,  3]  },
  { kw: "odyometri nedir",        vol: 22200, pos: [0, 0,  0,  15, 26] },
  { kw: "odyoloji nedir",         vol: 18100, pos: [0, 41, 17, 7,  10] },
  { kw: "kulak çınlaması nasıl geçer", vol: 12100, pos: [0, 0, 0, 0, 7] },
  { kw: "demans",                 vol: 9900,  pos: [90, 0, 0, 0, 0]    },
  { kw: "odyoloji",               vol: 9900,  pos: [0, 0,  26, 18, 41] },
  { kw: "tinnitus nedir",         vol: 8100,  pos: [0, 0,  0,  0,  35] },
  { kw: "odyometri",              vol: 8100,  pos: [0, 0,  0,  20, 33] },
  { kw: "tinnitus",               vol: 6600,  pos: [0, 0,  0,  0,  38] },
  { kw: "idis",                   vol: 6600,  pos: [4, 0,  0,  0,  0]  },
  { kw: "kulak tıkanıklığı",      vol: 5400,  pos: [0, 0,  45, 0,  15] },
  { kw: "kulak kaşıntısı neden olur", vol: 5400, pos: [0, 35, 14, 41, 11] },
];

// ─── Illüstrasyon (canlı entegrasyon sonraki fazda) ───────────────────────
const BACKLINKS = [
  { domain: "saglik.gov.tr",     dr: 88, refs: 2,  type: "dofollow", anchor: "işitme cihazı merkezleri",        first: "Şub 14" },
  { domain: "milliyet.com.tr",   dr: 90, refs: 5,  type: "dofollow", anchor: "IDIS İşitme",                     first: "Mar 02" },
  { domain: "hurriyet.com.tr",   dr: 91, refs: 3,  type: "dofollow", anchor: "işitme cihazı",                   first: "Mar 18" },
  { domain: "sozcu.com.tr",      dr: 87, refs: 2,  type: "dofollow", anchor: "IDIS İşitme Cihazları",           first: "Şub 28" },
  { domain: "saglikaktuel.com",  dr: 64, refs: 8,  type: "dofollow", anchor: "işitme merkezi",                  first: "Oca 11" },
  { domain: "wikipedia.org",     dr: 96, refs: 1,  type: "nofollow", anchor: "idis.com.tr",                     first: "Eki 22" },
  { domain: "ekolay.net",        dr: 58, refs: 4,  type: "dofollow", anchor: "Türkiye'nin en büyük ağı",        first: "Şub 02" },
];

const TECH = [
  { c: "İndekslenebilir sayfa",     v: 184, total: 198, tone: "ok",   note: "%93 indeksli" },
  { c: "Crawl hatası (4xx/5xx)",    v: 6,   total: 198, tone: "warn", note: "%3 — yönlendirme planı gerekli" },
  { c: "Mobil uyumluluk",           v: 198, total: 198, tone: "ok",   note: "Tüm sayfalar geçti" },
  { c: "Core Web Vitals (LCP)",     v: 71,  total: 100, tone: "warn", note: "%29 iyileştirme gerekli" },
  { c: "Core Web Vitals (INP)",     v: 84,  total: 100, tone: "ok",   note: "%84 iyi" },
  { c: "Core Web Vitals (CLS)",     v: 92,  total: 100, tone: "ok",   note: "%92 iyi" },
  { c: "Schema kapsamı",            v: 42,  total: 198, tone: "warn", note: "%21 — LocalBusiness/FAQ eksik" },
  { c: "Bozuk iç bağlantı",         v: 12,  total: 0,   tone: "warn", note: "12 link düzeltilmeli" },
];

const AI_MENTIONS = [
  { engine: "ChatGPT",    cited: 0, share: 0, d: 0, queries: ["karşıyaka işitme cihazı öner", "izmir işitme merkezi", "en iyi işitme merkezi"] },
  { engine: "Perplexity", cited: 0, share: 0, d: 0, queries: ["istanbul işitme merkezi öner", "işitme cihazı tavsiyesi"] },
  { engine: "Google AIO", cited: 1, share: 2.1, d: +1, queries: ["idis işitme cihazları", "idis şubeleri"] },
  { engine: "Claude",     cited: 0, share: 0, d: 0, queries: ["türkiye işitme merkezi", "işitme cihazı markaları"] },
];

// ─── Dynamic data: fetched per range from /api/dashboard ─────────────────

const trFmt = (n) => Math.round(n).toLocaleString("tr-TR");
const trPct = (n) => `${n >= 0 ? "+" : ""}${n.toFixed(1)}%`;

function shapeDashboard(raw) {
  const snap = raw.snapshot || { current: {}, prior: {}, change: {} };
  const cur = snap.current || {};
  const prior = snap.prior || {};
  const ga4 = (raw.ga4Overview?.rows || [])[0] || {};

  const KPIS = [
    {
      l: "Organik tıklama (GSC)",
      v: trFmt(cur.clicks || 0),
      d: trPct(snap.change?.clicksPercent || 0),
      tone: (snap.change?.clicks || 0) >= 0 ? "up" : "down",
    },
    {
      l: "Gösterim (GSC)",
      v: trFmt(cur.impressions || 0),
      d: trPct(snap.change?.impressionsPercent || 0),
      tone: (snap.change?.impressions || 0) >= 0 ? "up" : "down",
    },
    {
      l: "Ortalama pozisyon",
      v: (cur.position || 0).toFixed(1),
      d: `${(snap.change?.position || 0) > 0 ? "+" : ""}${(snap.change?.position || 0).toFixed(1)}`,
      tone: (snap.change?.position || 0) <= 0 ? "up" : "down",
    },
    {
      l: "Aktif kullanıcı (GA4)",
      v: trFmt(ga4.activeUsers || 0),
      d: "—",
      tone: "up",
    },
  ];

  // Date rows come back unsorted; resort ascending and map
  const dateRows = (raw.dateRows?.rows || [])
    .slice()
    .sort((a, b) => (a.keys[0] < b.keys[0] ? -1 : 1));
  const TR_MONTHS = ["Oca","Şub","Mar","Nis","May","Haz","Tem","Ağu","Eyl","Eki","Kas","Ara"];
  const TRAFFIC = dateRows.map((r, i) => {
    const dateStr = r.keys[0]; // "2026-04-15"
    const dt = new Date(dateStr);
    return {
      d: i,
      date: dateStr,
      label: `${dt.getDate()} ${TR_MONTHS[dt.getMonth()]}`,
      clicks: r.clicks,
      imp: r.impressions,
    };
  });

  // Aggregate URL variants (https/http/www → same path) so the homepage doesn't appear 4×
  const pageMap = new Map();
  (raw.pageRows?.rows || []).forEach((r) => {
    const raw_url = r.keys[0] || "";
    const path = raw_url.replace(/^https?:\/\/[^/]+/, "") || "/";
    const existing = pageMap.get(path);
    if (existing) {
      existing.clicks += r.clicks;
      existing.imp += r.impressions;
      // weighted avg position by impressions
      existing.posSum += r.position * r.impressions;
      existing.impSum += r.impressions;
    } else {
      pageMap.set(path, {
        url: path,
        clicks: r.clicks,
        imp: r.impressions,
        posSum: r.position * r.impressions,
        impSum: r.impressions,
        d: 0,
      });
    }
  });
  const TOP_PAGES = Array.from(pageMap.values())
    .map((p) => ({
      url: p.url,
      clicks: p.clicks,
      imp: p.imp,
      ctr: +(p.imp ? (p.clicks / p.imp) * 100 : 0).toFixed(2),
      pos: +(p.impSum ? p.posSum / p.impSum : 0).toFixed(1),
      d: 0,
    }))
    .sort((a, b) => b.clicks - a.clicks)
    .slice(0, 10);

  const KEYWORDS = (raw.queryRows?.rows || []).slice(0, 15).map((r) => ({
    kw: r.keys[0] || "",
    pos: +r.position.toFixed(1),
    prev: +r.position.toFixed(1),
    vol: r.impressions,
    ctr: +r.ctr.toFixed(2),
    url: "/",
  }));

  return { KPIS, TRAFFIC, TOP_PAGES, KEYWORDS, period: { range: raw.range, days: raw.days } };
}

const DataContext = React.createContext({ loading: true, fetching: false, data: null, error: null });
const useDashData = () => React.useContext(DataContext);

// Stale-while-revalidate: keep previous data on screen during refetch.
// `loading` is true only on initial fetch (no data yet).
// `fetching` is true on every fetch (including refetches).
const DataProvider = ({ range, children }) => {
  const [state, setState] = React.useState({ loading: true, fetching: true, data: null, error: null });

  React.useEffect(() => {
    let cancelled = false;
    setState((s) => ({ ...s, fetching: true, error: null }));
    fetch(`/api/dashboard?range=${range}`)
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((raw) => {
        if (cancelled) return;
        setState({ loading: false, fetching: false, data: shapeDashboard(raw), error: null });
      })
      .catch((err) => {
        if (cancelled) return;
        setState((s) => ({ ...s, loading: !s.data, fetching: false, error: err.message }));
      });
    return () => {
      cancelled = true;
    };
  }, [range]);

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

Object.assign(window, {
  BRANDS, BACKLINKS, TECH, AI_MENTIONS, COMPETITORS, KEYWORD_OVERLAP,
  DataContext, DataProvider, useDashData,
});
