/* ============================================================
   APP SHELL — top tabs, theme toggle, global FBC selection.
   State persists in localStorage so a refresh keeps your place.
   ============================================================ */
const { useState: useS, useEffect: useE, useRef } = React;

function load(key, fallback) {
  try {const v = localStorage.getItem("fbc." + key);return v == null ? fallback : JSON.parse(v);}
  catch (e) {return fallback;}
}
function save(key, val) {try {localStorage.setItem("fbc." + key, JSON.stringify(val));} catch (e) {}}

/* ---------- Global "exclude owners" control (lives in the footer) ----------
   Lets the user drop specific franchise owners (data issues, closures, etc.)
   from EVERY tab at once. Selection persists and is pushed into the data
   layer via MM.setExcluded, so every metric, chart and table recalculates. */
function ExcludeOwners({ excluded, setExcluded }) {
  const [open, setOpen] = useS(false);
  const [q, setQ] = useS("");
  const ref = useRef(null);
  useE(() => {
    function onDoc(e) {if (ref.current && !ref.current.contains(e.target)) setOpen(false);}
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);
  const all = MM.allOwners;
  const set = new Set(excluded);
  function toggle(id) {
    const next = new Set(excluded);
    next.has(id) ? next.delete(id) : next.add(id);
    setExcluded([...next]);
  }
  const needle = q.trim().toLowerCase();
  const list = all.
  filter((o) => !needle || o.contact.toLowerCase().includes(needle) || o.city.toLowerCase().includes(needle) || o.state.toLowerCase().includes(needle) || o.name.toLowerCase().includes(needle)).
  slice(0, 60);
  return (
    <div className="excl" ref={ref}>
      <button className={"excl-btn" + (excluded.length ? " has" : "")} onClick={() => setOpen((v) => !v)} aria-expanded={open}>
        {excluded.length ? excluded.length + " owner" + (excluded.length !== 1 ? "s" : "") + " excluded" : "Exclude owners"}
        <span className="excl-chev" aria-hidden="true">{open ? "▾" : "▴"}</span>
      </button>
      {open &&
      <div className="excl-panel" role="dialog" aria-label="Exclude owners">
          <div className="excl-head">
            <span className="excl-title">Exclude owners from all views</span>
            <span className="excl-help">Hidden from every metric, chart and table — use for data issues or closed locations.</span>
          </div>
          <input className="excl-search" placeholder="Search owner, city, or state…" value={q} onChange={(e) => setQ(e.target.value)} autoFocus />
          {excluded.length > 0 &&
        <button className="excl-clear" onClick={() => setExcluded([])}>Clear all {excluded.length}</button>
        }
          <div className="excl-list">
            {list.map((o) =>
          <label key={o.id} className={"excl-opt" + (set.has(o.id) ? " on" : "")}>
                <input type="checkbox" checked={set.has(o.id)} onChange={() => toggle(o.id)} />
                <span className="excl-opt-main">
                  <span className="excl-opt-name">{o.contact}</span>
                  <span className="excl-opt-sub">{o.city}, {o.state} · {o.name.replace("Molly Maid of ", "")}</span>
                </span>
              </label>
          )}
            {list.length === 0 && <p className="excl-empty">No owners match “{q}”.</p>}
          </div>
        </div>
      }
    </div>);

}

const TABS = [
{ id: "performance", label: "Performance", short: "Perf", desc: "Revenue, royalty & EBITDA vs plan" },
{ id: "drivers", label: "Drivers", short: "Drivers", desc: "Conversion · Frequency · Retention · Engagement · NPS" },
{ id: "territory", label: "Book of Business", short: "Book", desc: "Map · owners · concerns" },
{ id: "fbo", label: "FBO Detail", short: "FBO", desc: "Single-owner coaching view" }];


function App() {
  const [tab, setTab] = useS(() => load("tab", "performance"));
  const [metric, setMetric] = useS(() => load("metric", "revenue"));
  const [fbcIds, setFbcIds] = useS(() => load("fbcIds", []));
  const [theme, setTheme] = useS(() => load("theme", "light"));
  const [excluded, setExcluded] = useS(() => load("excludedIds", []));
  const [detailOwnerId, setDetailOwnerId] = useS(() => load("detailOwnerId", null));

  useE(() => save("tab", tab), [tab]);
  useE(() => save("metric", metric), [metric]);
  useE(() => save("fbcIds", fbcIds), [fbcIds]);
  useE(() => save("excludedIds", excluded), [excluded]);
  useE(() => save("detailOwnerId", detailOwnerId), [detailOwnerId]);
  useE(() => {save("theme", theme);document.documentElement.setAttribute("data-theme", theme);}, [theme]);

  // keep the data layer in sync with the user's exclusions on every render,
  // BEFORE the pages below read any metrics through MM.*
  MM.setExcluded(excluded);

  // any owner drawer (Performance / Book of Business) can jump straight to the
  // full coaching page with that owner preselected.
  function openFboDetail(id) {setDetailOwnerId(id);setTab("fbo");window.scrollTo({ top: 0 });}
  window.__openFboDetail = openFboDetail;

  function focusFbc(id) {setFbcIds([id]);setTab("territory");}

  return (
    <div className="app">
      <header className="topbar">
        <div className="topbar-inner" data-comment-anchor="be97607e1e-div-35-9">
          <div className="brand">
            <img className="brand-logo" src="assets/molly-maid-lotus-mark.png" alt="Molly Maid" data-comment-anchor="3fb41b3938-img-37-13" />
          </div>
          <nav className="tabs" role="tablist">
            {TABS.map((t) =>
            <button key={t.id} role="tab" aria-selected={tab === t.id}
            className={"tab" + (tab === t.id ? " active" : "")} onClick={() => setTab(t.id)}>
              <span className="tab-label">{t.label}</span>
              <span className="tab-label-short">{t.short}</span>
              <span className="tab-desc">{t.desc}</span>
            </button>
            )}
          </nav>
          <div className="topbar-right">
            <button className="theme-toggle" onClick={() => setTheme((t) => t === "light" ? "dark" : "light")}
            aria-label="Toggle light or dark theme" title="Toggle light / dark">
              <span className="theme-ic light-only" aria-hidden="true">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" /></svg>
              </span>
              <span className="theme-ic dark-only" aria-hidden="true">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z" /></svg>
              </span>
            </button>
          </div>
        </div>
      </header>

      <main className="main" data-comment-anchor="83f03d6a2b-main-135-7">
        {tab === "performance" && <PerformancePage metric={metric} setMetric={setMetric} fbcIds={fbcIds} setFbcIds={setFbcIds} />}
        {tab === "drivers" && <DriversPage onFocusFbc={focusFbc} />}
        {tab === "territory" && <TerritoryPage fbcIds={fbcIds} setFbcIds={setFbcIds} />}
        {tab === "fbo" && <FBODetailPage ownerId={detailOwnerId} setOwnerId={setDetailOwnerId} />}
      </main>

      <footer className="appfoot" data-comment-anchor="0418a522bf-footer-68-7">
        <span>Molly Maid® · FBC performance dashboard · <span className="appfoot-asof">As of <b>Week {MM.config.currentWeek}</b> · {MM.config.year}</span></span>
        <div className="appfoot-right">
          <ExcludeOwners excluded={excluded} setExcluded={setExcluded} />
          <span className="appfoot-mock">Mock data — built to swap for live data. A clean you can count on.®</span>
        </div>
      </footer>
    </div>);

}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);