/* global React */

// =====================================================================
//  SINGLE SOURCE OF TRUTH for every stat on the page.
//
//  Numbers live in a Google Sheet that is "Published to web" as CSV.
//  The site fetches that CSV on load and follows whatever is in the
//  Sheet — edit the Sheet (even from your phone) and the site updates,
//  no code change or deploy needed.
//
//  If the Sheet is empty / offline / misconfigured, the DEFAULTS below
//  are used instead, so the page can never break.
//
//  Sheet layout — two columns, header row "key,value", then:
//    instagram            37300
//    facebook             21000
//    tiktok               13900
//    twitter              9500
//    linkedin             3400
//    monthly_impressions  6M
//    avg_engagement       14%
//    geo_indonesia        57
//    geo_international     43
//
//  Note: rates are intentionally NOT in the Sheet — every package on the
//  page shows "Call for price" and is quoted per brief.
// =====================================================================

// ↓ Paste your Google Sheet "Publish to web → CSV" link between the quotes.
//   Leave empty to just use the DEFAULTS below.
const SHEET_CSV_URL = "https://docs.google.com/spreadsheets/d/e/2PACX-1vQK3AK9eWSGzfgBiQjeReWqsNpMFiUQv_CQ_gVogC9fTufh4tcIw8yclPJqKc-xPduyuewlPBXqL6DC/pub?gid=0&single=true&output=csv";

const DEFAULTS = {
  // follower counts (plain numbers — formatted + summed automatically)
  instagram: 37300,
  facebook: 21000,
  tiktok: 13900,
  twitter: 9500,
  linkedin: 3400,
  // headline metrics (plain text, no trailing "+")
  monthly_impressions: "6M",
  avg_engagement: "14%",
  // geography split (numbers, should add up to 100)
  geo_indonesia: 57,
  geo_international: 43,
};

// ── tiny reactive store ──────────────────────────────────────────────
const _store = { data: { ...DEFAULTS }, listeners: new Set() };
function _setData(patch) {
  _store.data = { ..._store.data, ...patch };
  _store.listeners.forEach((fn) => fn());
}

// ── minimal CSV parser (handles quoted fields) ───────────────────────
function parseCSV(text) {
  const rows = [];
  let row = [], field = "", inQuotes = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (inQuotes) {
      if (c === '"') {
        if (text[i + 1] === '"') { field += '"'; i++; }
        else inQuotes = false;
      } else field += c;
    } else if (c === '"') {
      inQuotes = true;
    } else if (c === ",") {
      row.push(field); field = "";
    } else if (c === "\n") {
      row.push(field); rows.push(row); row = []; field = "";
    } else if (c !== "\r") {
      field += c;
    }
  }
  if (field.length || row.length) { row.push(field); rows.push(row); }
  return rows;
}

function loadSiteData() {
  if (!SHEET_CSV_URL) return; // no Sheet configured → keep DEFAULTS
  fetch(SHEET_CSV_URL, { cache: "no-store" })
    .then((r) => (r.ok ? r.text() : Promise.reject(r.status)))
    .then((text) => {
      const patch = {};
      parseCSV(text).forEach(([key, value]) => {
        const k = (key || "").trim().toLowerCase();
        if (!(k in DEFAULTS)) return; // skip header / unknown rows
        const v = (value || "").trim();
        if (v === "") return;
        patch[k] = typeof DEFAULTS[k] === "number"
          ? Number(v.replace(/[^0-9.]/g, ""))
          : v;
      });
      if (Object.keys(patch).length) _setData(patch);
    })
    .catch(() => { /* unreachable Sheet → keep DEFAULTS silently */ });
}

// ── hook: re-renders the component when fresh data arrives ────────────
function useSiteData() {
  const [, force] = React.useReducer((n) => n + 1, 0);
  React.useEffect(() => {
    _store.listeners.add(force);
    return () => _store.listeners.delete(force);
  }, []);
  return _store.data;
}

// ── derived: combined audience = sum of the 5 platforms ──────────────
function combinedFollowers(d) {
  return ["instagram", "facebook", "tiktok", "twitter", "linkedin"]
    .reduce((sum, k) => sum + (Number(d[k]) || 0), 0);
}

loadSiteData();

window.useSiteData = useSiteData;
window.combinedFollowers = combinedFollowers;
