// ─────────────────────────────────────────────────────────────────────────
// Honda — Otomotiv / Motosiklet SEO Dashboard (honda.com.tr)
// Dynamic data: GSC + GA4 (live via /api/dashboard?range=...)
// Static (Semrush TR DB, 2026-06-05):
//   SEMRUSH_OVERVIEW (organik alanlar) + KEYWORD_OVERLAP gerçek veridir.
//   COMPETITORS, BACKLINKS ve overview'in backlink alanlari (authorityScore,
//   totalBacklinks, refDomains, dofollowPct) Semrush API unit yetersizligi
//   nedeniyle henuz cekilemedi -> null/bos, UI dürüst "veri bekleniyor" gösterir.
//   Unit yenilenince: domain_organic_organic, backlinks_overview, backlinks_refdomains.
// Renk paleti: renk körü uyumlu (Okabe-Ito) · kirmizi+yesil ikilisi yok.
// Illüstrasyon: TECH, AI_MENTIONS (entegrasyon sonraki fazda)
// ─────────────────────────────────────────────────────────────────────────

const BRANDS = [
  { id: "honda",      name: "Honda",      url: "honda.com.tr",      initials: "HO", color: "#D55E00", logoTile: "hon", logoName: "da" },
  { id: "toyota",     name: "Toyota",     url: "toyota.com.tr",     initials: "TO", color: "#0072B2" },
  { id: "renault",    name: "Renault",    url: "renault.com.tr",    initials: "RE", color: "#E69F00" },
  { id: "ford",       name: "Ford",       url: "ford.com.tr",       initials: "FO", color: "#56B4E9" },
  { id: "fiat",       name: "Fiat",       url: "fiat.com.tr",       initials: "FI", color: "#009E73" },
  { id: "volkswagen", name: "Volkswagen", url: "vw.com.tr",         initials: "VW", color: "#CC79A7" },
];

// ─── Semrush Overview (TR DB, 2026-06-05) ────────────────────────────────
// organik alanlar GERÇEK Semrush verisi. backlink alanlari (authorityScore,
// totalBacklinks, refDomains, dofollowPct) API unit yenilenince doldurulacak.
const SEMRUSH_OVERVIEW = {
  organicKeywords: 65034,
  organicTraffic: 1036081,
  organicTrafficCost: 74767,
  paidKeywords: 306,
  paidTraffic: 74359,
  paidTrafficCost: 4474,
  authorityScore: null,
  totalBacklinks: null,
  refDomains: null,
  dofollowPct: null,
  database: "TR",
  refreshedAt: "2026-06-05",
};

// ─── Competitor Share-of-Voice ───────────────────────────────────────────
// Semrush domain_organic_organic raporu API unit yetersizligi nedeniyle
// cekilemedi. Rakip organik trafik/SoV verisi gelince doldurulacak.
// Uydurma metrik girilmedi -> bos. UI "veri bekleniyor" gösterir.
const COMPETITORS = [];

// ─── honda.com.tr'nin en yüksek organik trafiği getiren keyword'leri ──────
// GERÇEK Semrush TR verisi (2026-06-05). pos sırası: [Honda, rakip1..4].
// Rakip pozisyonlari (domain_domains gap raporu) cekilemediginden 0.
const KEYWORD_OVERLAP = [
  { kw: "honda",                     vol: 368000, pos: [1, 0, 0, 0, 0] },
  { kw: "honda civic",               vol: 368000, pos: [2, 0, 0, 0, 0] },
  { kw: "hornet",                    vol: 201000, pos: [4, 0, 0, 0, 0] },
  { kw: "honda hornet",              vol: 201000, pos: [4, 0, 0, 0, 0] },
  { kw: "honda motor",               vol: 135000, pos: [1, 0, 0, 0, 0] },
  { kw: "honda fiyat listesi",       vol: 110000, pos: [1, 0, 0, 0, 0] },
  { kw: "honda fiyat",               vol: 110000, pos: [1, 0, 0, 0, 0] },
  { kw: "honda crv",                 vol:  74000, pos: [2, 0, 0, 0, 0] },
  { kw: "honda cr-v",                vol:  74000, pos: [2, 0, 0, 0, 0] },
  { kw: "pcx",                       vol:  60500, pos: [2, 0, 0, 0, 0] },
  { kw: "pcx 125",                   vol:  60500, pos: [2, 0, 0, 0, 0] },
  { kw: "honda motosiklet",          vol:  40500, pos: [1, 0, 0, 0, 0] },
  { kw: "honda pcx",                 vol:  40500, pos: [1, 0, 0, 0, 0] },
  { kw: "honda motor fiyat listesi", vol:  40500, pos: [1, 0, 0, 0, 0] },
  { kw: "honda forza",               vol:  14800, pos: [1, 0, 0, 0, 0] },
];

// ─── Top referring domains ───────────────────────────────────────────────
// Semrush backlinks_refdomains raporu API unit yetersizligi nedeniyle
// cekilemedi. Unit yenilenince doldurulacak. Uydurma link girilmedi -> bos.
const BACKLINKS = [];

// ─── 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 SUV modelleri", "honda civic yorum", "uygun fiyatlı otomobil önerisi"] },
  { engine: "Perplexity", cited: 0, share: 0, d: 0, queries: ["honda pcx vs forza", "şehir içi motosiklet önerisi"] },
  { engine: "Google AIO", cited: 0, share: 0, d: 0, queries: ["honda crv güvenilir mi", "honda yetkili servis"] },
  { engine: "Claude",     cited: 0, share: 0, d: 0, queries: ["hibrit otomobil karşılaştırma", "honda hornet özellikleri"] },
];

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