/* global React, PinContext, InsightsLoop, CurateWorkspace */
// =========================================================
// v4 · Merged Insights tab.
// One tab, two modes:
//   · Curate  (CSM-only)  — findings pool + story outline.
//   · Preview (client)    — the published reading view, reusing
//                           the existing InsightsLoop renderer.
// The toggle persists in localStorage so a refresh keeps the mode.
// =========================================================

const V4_MODE_KEY = "gola-v4-insights-mode";

// Adapt the published sections into the shape InsightsLoop reads
// (it expects curated insights with .findings / .findingsException /
// .findingsGroup), then feed it through a scoped PinContext so the
// reading view, exceptions, consistent-groups and Ask MakerLab all
// work unchanged.
function PreviewClient({ store }) {
  const live = store.sections.filter((s) => s.status === "live");

  const previewStore = React.useMemo(() => ({
    ...store,
    readOnly: true,
    insights: live.map((s) => ({
      id: s.id,
      num: s.num,
      objs: s.objs,
      nav: s.title || s.short,
      source: "curated",
      title: s.title,
      tagline: "",
      action: s.action,
      ev: [],
      findings: s.findings,
      findingsException: s.findingsException,
      findingsGroup: s.findingsGroup,
      findingsNote: null,
    })),
    // headline edits in the client preview write back to the section
    setHeadline: (id, text) => store.editHeadline(id, text),
    // publish controls live in Curate, not the client view
    publishInsight: () => {},
  }), [store, live]);

  if (live.length === 0) {
    return (
      <div className="mi-empty">
        <div className="mi-empty__title">No insights published yet</div>
        <div className="mi-empty__sub">Switch to <b>Curate</b> to group findings, synthesize, and publish them into this client view.</div>
      </div>
    );
  }

  return (
    <PinContext.Provider value={previewStore}>
      <InsightsLoop />
    </PinContext.Provider>
  );
}

function MergedInsights({ store }) {
  const [mode, setMode] = React.useState(() => {
    try {
      var q = new URLSearchParams(window.location.search).get("view");
      if (q === "client") return "preview";
      if (q === "curate") return "curate";
      return window.localStorage.getItem(V4_MODE_KEY) || "preview";
    } catch (e) { return "preview"; }
  });
  const setModePersist = (m) => {
    setMode(m);
    try { window.localStorage.setItem(V4_MODE_KEY, m); } catch (e) {}
  };

  const live = store.sections.filter((s) => s.status === "live").length;
  const drafts = store.sections.length - live;

  return (
    <div className="mi">
      {/* mode bar */}
      <div className="mi-modebar">
        <div className="mi-seg" role="tablist" aria-label="Insights mode">
          <button className={"mi-seg__btn" + (mode === "curate" ? " is-on" : "")} onClick={() => setModePersist("curate")} role="tab" aria-selected={mode === "curate"}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M3 5h7M3 12h7M3 19h11"/><circle cx="17" cy="6" r="2"/><circle cx="19" cy="13" r="2"/></svg>
            Curate
          </button>
          <button className={"mi-seg__btn" + (mode === "preview" ? " is-on" : "")} onClick={() => setModePersist("preview")} role="tab" aria-selected={mode === "preview"}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
            Client view
          </button>
        </div>
        <div className="mi-modebar__meta">
          {mode === "curate" && <span className="mi-modebar__counts">{live} live · {drafts} draft</span>}
        </div>
      </div>

      <div className="mi-body">
        {mode === "curate" ? <CurateWorkspace store={store} /> : <PreviewClient store={store} />}
      </div>
    </div>
  );
}

Object.assign(window, { MergedInsights, PreviewClient });
