// ─────────────────────────────────────────────────────────────────────────
// Justinbeauty — Kozmetik / Güzellik SEO Dashboard
// Dynamic data: GSC (live via /api/dashboard?range=...). GA4 placeholder
// (service account property'ye eklendiğinde otomatik canlıya döner).
// Static (Semrush TR DB — refresh edildiğinde dolacak):
//   COMPETITORS, KEYWORD_OVERLAP, BACKLINKS, SEMRUSH_OVERVIEW
// Illüstrasyon: TECH, AI_MENTIONS (entegrasyon sonraki fazda)
// ─────────────────────────────────────────────────────────────────────────

const BRANDS = [
  { id: "justinbeauty", name: "Justinbeauty", url: "justinbeauty.com",  initials: "JB", color: "#D4357A", logoTile: "just", logoName: "inbeauty" },
  { id: "korendy",      name: "Korendy",      url: "korendy.com.tr",   initials: "KR", color: "#FF6B9D" },
  { id: "mclub",        name: "Mclub",        url: "mclub.com.tr",     initials: "MC", color: "#3A6F89" },
  { id: "purest",       name: "Purest",       url: "thepurestsolutions.com", initials: "PS", color: "#0E7C66" },
  { id: "badenatural",  name: "Bade Natural", url: "badenatural.com",  initials: "BN", color: "#7B5E3C" },
  { id: "vionine",      name: "Vionine",      url: "vionine.com",      initials: "VN", color: "#A85A8A" },
];

// ─── Semrush Overview (TR DB, refreshed 2026-05-05) ──────────────────────
const SEMRUSH_OVERVIEW = {
  organicKeywords: 6952,
  organicTraffic: 35629,
  organicTrafficCost: 42752,
  paidKeywords: 49,
  paidTraffic: 1496,
  paidTrafficCost: 3205,
  authorityScore: 31,
  totalBacklinks: 2445,
  refDomains: 358,
  dofollowPct: 64.4,
  database: "TR",
  refreshedAt: "2026-05-05",
};

// ─── Competitor Share-of-Voice (Semrush TR DB, 2026-05-05) ───────────────
// clicks = aylık organik trafik tahmini, kw = sıralanan keyword sayısı,
// dr = Semrush Authority Score, share = bu 6 marka arasındaki organik pay (%).
const COMPETITORS = [
  { name: "Justinbeauty", clicks:  35629, kw:  6952, dr: 31, share:  5.2, you: true },
  { name: "Korendy",      clicks: 263005, kw: 29936, dr: 36, share: 38.6 },
  { name: "Mclub",        clicks: 157788, kw: 11641, dr: 25, share: 23.1 },
  { name: "Purest",       clicks: 101619, kw:  7110, dr: 38, share: 14.9 },
  { name: "Bade Natural", clicks:  69860, kw: 11979, dr: 38, share: 10.2 },
  { name: "Vionine",      clicks:  53726, kw:  9361, dr: 40, share:  7.9 },
];

// ─── Justinbeauty'nin top 15 organic kw (Semrush TR, tr_desc) ────────────
// pos sırası: [Justinbeauty, Korendy, Mclub, Purest, Bade Natural, Vionine].
// Faz 2: rakip pozisyonları için domain_domains gap raporu çekilecek.
const KEYWORD_OVERLAP = [
  { kw: "justin beauty",            vol:  8100, pos: [1, 0, 0, 0, 0, 0] },
  { kw: "jel tırnak",               vol: 12100, pos: [1, 0, 0, 0, 0, 0] },
  { kw: "aromatica aloe vera gel",  vol:   880, pos: [1, 0, 0, 0, 0, 0] },
  { kw: "peeling",                  vol: 18100, pos: [7, 0, 0, 0, 0, 0] },
  { kw: "niacinamide serum",        vol: 12100, pos: [3, 0, 0, 0, 0, 0] },
  { kw: "village 11 factory",       vol:  1000, pos: [1, 0, 0, 0, 0, 0] },
  { kw: "kore güneş kremi",         vol:  3600, pos: [2, 0, 0, 0, 0, 0] },
  { kw: "benton güneş kremi",       vol:   590, pos: [1, 0, 0, 0, 0, 0] },
  { kw: "abib",                     vol:   590, pos: [1, 0, 0, 0, 0, 0] },
  { kw: "emülsiyon nedir",          vol:  5400, pos: [2, 0, 0, 0, 0, 0] },
  { kw: "su bazlı güneş kremi",     vol:  3600, pos: [3, 0, 0, 0, 0, 0] },
  { kw: "hint yağı ne işe yarar",   vol: 18100, pos: [3, 0, 0, 0, 0, 0] },
  { kw: "jel",                      vol:  4400, pos: [3, 0, 0, 0, 0, 0] },
  { kw: "kore cilt bakımı",         vol:  1600, pos: [2, 0, 0, 0, 0, 0] },
  { kw: "hint yağı faydaları",      vol: 22200, pos: [4, 0, 0, 0, 0, 0] },
];

// ─── Top referring domains (Semrush, Authority Score sırasıyla) ──────────
const BACKLINKS = [
  { domain: "yahoo.com",         dr: 100, refs:  5, type: "dofollow", anchor: "justinbeauty.com", first: "Eyl 2025" },
  { domain: "yandex.com",        dr:  96, refs:  2, type: "dofollow", anchor: "justinbeauty.com", first: "Kas 2025" },
  { domain: "yandex.com.tr",     dr:  91, refs:  3, type: "dofollow", anchor: "justinbeauty",     first: "Eyl 2025" },
  { domain: "aptoide.com",       dr:  78, refs: 62, type: "dofollow", anchor: "Justin Beauty",    first: "Ağu 2024" },
  { domain: "oggusto.com",       dr:  58, refs:  4, type: "dofollow", anchor: "justinbeauty.com", first: "Haz 2025" },
  { domain: "vogue.com.tr",      dr:  54, refs:  4, type: "dofollow", anchor: "Justinbeauty",     first: "Şub 2026" },
  { domain: "iyzico.com",        dr:  47, refs:  2, type: "dofollow", anchor: "justinbeauty.com", first: "Eyl 2025" },
  { domain: "fashfed.com",       dr:  45, refs:  3, type: "dofollow", anchor: "Justinbeauty",     first: "Kas 2025" },
  { domain: "kolektifhouse.co",  dr:  41, refs:  6, type: "dofollow", anchor: "Justinbeauty",     first: "Ağu 2025" },
  { domain: "sitelike.org",      dr:  41, refs: 29, type: "dofollow", anchor: "justinbeauty.com", first: "Eyl 2025" },
];

// ─── Illüstrasyon (canlı entegrasyon sonraki fazda) ───────────────────────
const TECH = [
  { c: "İndekslenebilir sayfa",     v: 0, total: 0,   tone: "ok",   note: "Site-audit entegrasyonu beklemede" },
  { c: "Crawl hatası (4xx/5xx)",    v: 0, total: 0,   tone: "warn", note: "Site-audit entegrasyonu beklemede" },
  { c: "Mobil uyumluluk",           v: 0, total: 0,   tone: "ok",   note: "Site-audit entegrasyonu beklemede" },
  { c: "Core Web Vitals (LCP)",     v: 0, total: 100, tone: "warn", note: "PSI entegrasyonu beklemede" },
  { c: "Core Web Vitals (INP)",     v: 0, total: 100, tone: "warn", note: "PSI entegrasyonu beklemede" },
  { c: "Core Web Vitals (CLS)",     v: 0, total: 100, tone: "warn", note: "PSI entegrasyonu beklemede" },
  { c: "Schema kapsamı",            v: 0, total: 0,   tone: "warn", note: "Site-audit entegrasyonu beklemede" },
  { c: "Bozuk iç bağlantı",         v: 0, total: 0,   tone: "warn", note: "Site-audit entegrasyonu beklemede" },
];

const AI_MENTIONS = [
  { engine: "ChatGPT",    cited: 0, share: 0, d: 0, queries: ["en iyi kozmetik markaları", "justinbeauty yorum", "cilt bakım önerisi"] },
  { engine: "Perplexity", cited: 0, share: 0, d: 0, queries: ["online makyaj alışverişi", "kaliteli ruj markası"] },
  { engine: "Google AIO", cited: 0, share: 0, d: 0, queries: ["justinbeauty güvenilir mi", "kozmetik iade politikası"] },
  { engine: "Claude",     cited: 0, share: 0, d: 0, queries: ["online kozmetik satın alma", "cilt bakımı önerisi"] },
];

// ─── 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",
    },
  ];

  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];
    const dt = new Date(dateStr);
    return {
      d: i,
      date: dateStr,
      label: `${dt.getDate()} ${TR_MONTHS[dt.getMonth()]}`,
      clicks: r.clicks,
      imp: r.impressions,
    };
  });

  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;
      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: "/",
  }));

  // ─── Aylık organik trafik (son 12 ay, GSC date dim aggregated) ─────────
  // Kısmi aylar (ilk ay = window başlangıcı, son ay = içinde bulunulan ay) işaretlenir.
  const monthMap = new Map();
  (raw.monthlyDateRows?.rows || []).forEach((r) => {
    const dateStr = r.keys[0] || "";
    const ym = dateStr.slice(0, 7); // "2026-04"
    if (!ym) return;
    const acc = monthMap.get(ym) || { ym, clicks: 0, imp: 0, days: 0 };
    acc.clicks += r.clicks || 0;
    acc.imp += r.impressions || 0;
    acc.days += 1;
    monthMap.set(ym, acc);
  });
  const today = new Date();
  const currentYM = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}`;
  const MONTHLY_TRAFFIC = Array.from(monthMap.values())
    .sort((a, b) => (a.ym < b.ym ? -1 : 1))
    .map((m, idx, arr) => {
      const [y, mo] = m.ym.split("-");
      const dt = new Date(+y, +mo - 1, 1);
      const daysInMonth = new Date(+y, +mo, 0).getDate();
      const isCurrentMonth = m.ym === currentYM;
      // İlk ay window'un kesildiği yerse (gün sayısı ay toplamından az) kısmi sayılır.
      const isWindowStart = idx === 0 && m.days < daysInMonth;
      const partial = isCurrentMonth || isWindowStart;
      return {
        ym: m.ym,
        label: `${TR_MONTHS[dt.getMonth()]} ${String(y).slice(2)}`,
        clicks: m.clicks,
        imp: m.imp,
        days: m.days,
        daysInMonth,
        partial,
      };
    });

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

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

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, SEMRUSH_OVERVIEW,
  DataContext, DataProvider, useDashData,
});
