// Hotel Contacts — live data loader (READ-ONLY) via the same-origin proxy.
// The browser fetches /api/sheet?src=hotels; the real source is resolved
// server-side (functions/api/sheet.js), so no source ID ships in this bundle.
//
// Behaviour:
//   • online  → fetches the full live data via the proxy, groups by state.
//   • offline / blocked → falls back to the real seed sample baked in below,
//     so the prototype (and the standalone offline bundle) never looks broken.

const HOTEL_CSV_URL = "/api/sheet?src=hotels";

// Real rows sampled from the live sheet — used as the offline fallback seed.
const HOTEL_SEED = [
  { state: "Alabama",  city: "Huntsville, AL",  hotel: "AC Hotel Huntsville Downtown",            email: "katelyn.aitken@marriott.com", phone: "1-256-836-7776", address: "435 Williams Ave SW, Huntsville, AL 35801" },
  { state: "Alabama",  city: "Huntsville, AL",  hotel: "Homewood Suites by Hilton Huntsville",     email: "ashley.elias@hilton.com",     phone: "1-256-539-1445", address: "714 Gallatin St SW, Huntsville, AL 35801" },
  { state: "Alabama",  city: "Huntsville, AL",  hotel: "Hampton Inn & Suites Huntsville Downtown", email: "ashley.elias@hilton.com",     phone: "1-256-270-9120", address: "313 Clinton Ave W, Huntsville, AL 35801" },
  { state: "Alaska",   city: "Anchorage, AK",   hotel: "Hilton Anchorage",                          email: "marelda.scott@hilton.com",    phone: "1-907-272-7411", address: "500 W 3rd Ave, Anchorage, AK 99501" },
  { state: "Alaska",   city: "Anchorage, AK",   hotel: "Aloft Anchorage",                           email: "sierra.piazza@jlhotelgroup.com", phone: "1-907-273-3000", address: "310 W 36th Ave, Anchorage, AK 99503" },
  { state: "Alaska",   city: "Anchorage, AK",   hotel: "Embassy Suites by Hilton Anchorage",        email: "jon.butzke@hilton.com",       phone: "1-907-332-7000", address: "600 E Benson Blvd, Anchorage, AK 99503" },
  { state: "Arizona",  city: "Flagstaff, AZ",   hotel: "Hyatt Place Flagstaff",                     email: "Kateb@IMMhotels.com",         phone: "1-928-433-6930", address: "397 S Malpais Ln, Flagstaff, AZ 86001" },
  { state: "Arizona",  city: "Flagstaff, AZ",   hotel: "DoubleTree by Hilton Flagstaff",            email: "Belen.Mendez@hilton.com",     phone: "1-928-773-8888", address: "1175 W Rte 66, Flagstaff, AZ 86001" },
  { state: "Arizona",  city: "Scottsdale, AZ",  hotel: "Canopy by Hilton Scottsdale Old Town",      email: "tiffany.nguyen2@hilton.com",  phone: "1-480-590-3864", address: "7142 E 1st St, Scottsdale, AZ 85251" },
  { state: "Arizona",  city: "Scottsdale, AZ",  hotel: "Omni Scottsdale Resort & Spa-Montelucia",   email: "phxrst.leads@omnihotels.com", phone: "1-480-627-3200", address: "4949 E Lincoln Dr, Scottsdale, AZ 85253" },
  { state: "California", city: "Anaheim, CA",   hotel: "Hotel Indigo Anaheim",                      email: "cleofe.saruca@winwinhotels.com", phone: "", address: "" },
  { state: "California", city: "Bakersfield, CA", hotel: "DoubleTree by Hilton Bakersfield",        email: "lori.labare@dtbakersfield.com",  phone: "", address: "" },
];

// --- CSV parser (handles quoted fields, embedded commas, doubled quotes) ---
function parseHotelCSV(text) {
  const rows = [];
  let row = [], field = "", i = 0, inQ = false;
  while (i < text.length) {
    const c = text[i];
    if (inQ) {
      if (c === '"') {
        if (text[i + 1] === '"') { field += '"'; i += 2; continue; }
        inQ = false; i++; continue;
      }
      field += c; i++; continue;
    }
    if (c === '"') { inQ = true; i++; continue; }
    if (c === ",") { row.push(field); field = ""; i++; continue; }
    if (c === "\r") { i++; continue; }
    if (c === "\n") { row.push(field); rows.push(row); row = []; field = ""; i++; continue; }
    field += c; i++;
  }
  if (field.length || row.length) { row.push(field); rows.push(row); }
  return rows;
}

// Sheet layout: A=State section, B=City, C=Hotel, D=Email, E=Phone, F=Address.
// State names sit alone in column A; hotels have A empty and B/C filled.
function buildHotelRows(cells) {
  const out = [];
  let curState = "";
  for (const r of cells) {
    const A = (r[0] || "").trim();
    const B = (r[1] || "").trim();
    const C = (r[2] || "").trim();
    const D = (r[3] || "").trim();
    const E = (r[4] || "").trim();
    const F = (r[5] || "").trim();
    if (C === "Hotel" && B === "City") continue;          // header row
    if (A && !C) {                                         // section row
      if (A.toUpperCase() === "USA") continue;             // country header
      curState = A;
      continue;
    }
    if (!C) continue;                                      // blank
    out.push({ state: curState, city: B, hotel: C, email: D, phone: E, address: F });
  }
  return out;
}

// Cached fetch — runs once, shared by desktop + mobile.
let _hotelsPromise = null;
function loadHotels() {
  if (_hotelsPromise) return _hotelsPromise;
  _hotelsPromise = (async () => {
    const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
    const t = ctrl ? setTimeout(() => ctrl.abort(), 9000) : null;
    try {
      const res = await fetch(HOTEL_CSV_URL, ctrl ? { signal: ctrl.signal } : undefined);
      if (!res.ok) throw new Error("HTTP " + res.status);
      const text = await res.text();
      const rows = buildHotelRows(parseHotelCSV(text));
      if (!rows.length) throw new Error("empty sheet");
      return rows;
    } finally { if (t) clearTimeout(t); }
  })();
  return _hotelsPromise;
}

// React hook — seed first, then swap to live data when it arrives.
function useHotels() {
  const [s, setS] = React.useState(() => ({ rows: HOTEL_SEED, status: "loading" }));
  React.useEffect(() => {
    let alive = true;
    loadHotels()
      .then(rows => { if (alive) { window.HOTEL_ROWS = rows; setS({ rows, status: "live" }); } })
      .catch(() => { if (alive) setS({ rows: HOTEL_SEED, status: "sample" }); });
    return () => { alive = false; };
  }, []);
  return s;
}

// Group rows by state, preserving first-seen order.
function groupHotelsByState(rows) {
  const order = [], map = {};
  rows.forEach(h => { const k = h.state || "Other"; if (!map[k]) { map[k] = []; order.push(k); } map[k].push(h); });
  return order.map(state => ({ state, rows: map[state] }));
}

window.HOTEL_SEED = HOTEL_SEED;
window.HOTEL_ROWS = HOTEL_SEED;
Object.assign(window, { loadHotels, useHotels, groupHotelsByState });
