/* global window */
// =========================================================
// v4 · Curation model — bridges Findings → Insights.
// A "section" is a CSM-built group of findings that, once
// synthesized (interpretive headline + actionable reco) and
// published, becomes one insight in the client-facing view.
//
// Sections are seeded from the brand's four research objectives
// (the backbone / story arc). The CSM drags findings into them,
// synthesizes, edits, and publishes.
// =========================================================
(function () {
  // The 20 segment / retailer / age cuts that all hold the same
  // consideration pattern — surfaced as ONE collapsed "consistent
  // across segments" block rather than 20 separate finding cards.
  var CONSISTENT_GROUP = {
    label: "Consistent across segments",
    sub: "20 segment, retailer & age cuts hold the same consideration pattern (ES 0.06–0.11) — appeal isn't concentrated in one audience.",
    ids: [
      "sentiment_score|...|ALOHAS::lens.seg.consumer",
      "sentiment_score|...|Anthropologie::lens.seg.consumer",
      "sentiment_score|...|Autry::lens.seg.consumer",
      "sentiment_score|...|Gola::lens.seg.consumer",
      "sentiment_score|...|Salomon::lens.seg.consumer",
      "sentiment_score|...|Vans::lens.seg.consumer",
      "sentiment_score|...|18-24::lens.hierarchy.franchise",
      "sentiment_score|...|Amazon::lens.hierarchy.franchise",
      "sentiment_score|...|Anthropologie::lens.hierarchy.franchise",
      "sentiment_score|...|Gola::lens.hierarchy.franchise",
      "sentiment_score|...|Puma::lens.hierarchy.franchise",
      "sentiment_score|...|Specialty::lens.hierarchy.franchise",
      "sentiment_score|...|Veja::lens.seg.consumer",
      "sentiment_score|...|>=55::lens.gap.channel",
      "sentiment_score|...|ALOHAS::lens.gap.channel",
      "sentiment_score|...|Anthropologie::lens.gap.channel",
      "sentiment_score|...|Autry::lens.gap.channel",
      "sentiment_score|...|Salomon::lens.gap.channel",
      "sentiment_score|...|Vans::lens.gap.channel",
      "sentiment_score|...|Veja::lens.gap.channel",
    ],
  };

  // Authored "AI" synthesis per objective. Headlines are interpretive
  // (they read the data, they don't describe it); recommendations are
  // actionable. Custom sections (no objId) fall back to a generic synth.
  var SYNTH = {
    1: {
      title: "Awareness, not appeal, is Gola's ceiling — the same consideration holds across every segment we cut.",
      action: "Put Spring '28 media weight behind awareness in the premium / aspirational aisles. The appeal and its cross-segment consistency are already there — don't re-engineer the line to chase reach.",
    },
    2: {
      title: "The line is already pre-edited by demand — sell a decided core to an omni-channel, mix-price shopper.",
      action: "Anchor every account's sell-in with the proven core and merchandise for both-channel, mix-price behavior. Reserve the open slots for account flavor, not new bets.",
    },
    3: {
      title: "Materialization is the design lever — the same last wins or loses on its upper, not its shape.",
      action: "Brief Spring '28 development on fabric and surface treatment of the franchises you already have, and cut the mesh and heavy-quilt make-ups before they reach the line.",
    },
    4: {
      title: "There's one consumer, not four — every account agrees on the heroes and the floor.",
      action: "Lead all four accounts with the same heroes and use the department-store read as your conservative sell-in baseline; treat Gola-affinity scores as a ceiling, not a forecast.",
    },
  };

  // Generic fallback synthesis for CSM-created sections.
  function genericSynth(section) {
    var RF = window.REAL_FINDINGS;
    var idx = {};
    if (RF && RF.CLAIMS) RF.CLAIMS.forEach(function (f) { idx[f.id] = f; });
    var lead = (section.findings || []).map(function (id) { return idx[id]; }).filter(Boolean)[0];
    var n = (section.findings || []).length;
    return {
      title: lead
        ? lead.statement.replace(/\.$/, "") + " — and the grouped evidence points the same way."
        : "Group findings into this section, then synthesize.",
      action: n > 0
        ? "Decide the one action this pattern should drive for the brand, then make it specific to the team that owns it."
        : "",
    };
  }

  function synthesize(section) {
    if (section && section.objId && SYNTH[section.objId]) return SYNTH[section.objId];
    return genericSynth(section);
  }

  var OBJ = (window.GOLA && window.GOLA.OBJECTIVES) || [];
  function objShort(id) { var o = OBJ.find(function (x) { return x.id === id; }); return o ? o.short : ""; }
  function objText(id) { var o = OBJ.find(function (x) { return x.id === id; }); return o ? o.text : ""; }

  // The seeded backbone. Two sections ship "live" (already synthesized &
  // published) so the client Preview isn't empty; two ship as drafts so the
  // CSM curation loop (group → synthesize → edit → publish) is demonstrable.
  function seedSections() {
    return [
      {
        id: "sec-o1", num: "01", objId: 1, objs: [1], short: objShort(1), objText: objText(1),
        accent: "var(--chart-green)",
        title: SYNTH[1].title, action: SYNTH[1].action,
        findings: ["f.69f4f3be8c1bee84ade9c9d7|overall|question::lens.seg.consumer"],
        findingsException: null,
        findingsGroup: JSON.parse(JSON.stringify(CONSISTENT_GROUP)),
        synthesized: true, synthesizing: false, status: "draft", source: "curated",
      },
      {
        id: "sec-o2", num: "02", objId: 2, objs: [2], short: objShort(2), objText: objText(2),
        accent: "var(--chart-purple)",
        title: SYNTH[2].title, action: SYNTH[2].action,
        findings: [
          "f.69f4f3be8c1bee84ade9c9fb|overall|69f4f3be8c1bee84ade9c9ff::lens.seg.consumer",
          "f.69f4f3be8c1bee84ade9ca39|overall|69f4f3be8c1bee84ade9ca3c::lens.seg.consumer",
          "product_treatment|accounts::lens.account.perception",
        ],
        findingsException: null, findingsGroup: null,
        synthesized: true, synthesizing: false, status: "live", source: "curated",
      },
      {
        id: "sec-o3", num: "03", objId: 3, objs: [3], short: objShort(3), objText: objText(3),
        accent: "var(--chart-yellow)",
        title: "", action: "",
        findings: [
          "product_treatment|hawk::lens.design.treatment",
          "product_treatment|sprinter::lens.design.treatment",
          "product_treatment|amera::lens.design.treatment",
          "product_treatment|trakstar::lens.design.treatment",
        ],
        findingsException: {
          id: "product_treatment|celestra::lens.design.treatment",
          note: "The one exception that qualifies the headline: here the silhouette / construction caps the franchise — no treatment rescues the quilt.",
        },
        findingsGroup: null,
        synthesized: false, synthesizing: false, status: "draft", source: "curated",
      },
      {
        id: "sec-o4", num: "04", objId: 4, objs: [4], short: objShort(4), objText: objText(4),
        accent: "var(--chart-red)",
        title: SYNTH[4].title, action: SYNTH[4].action,
        findings: [
          "product_treatment|accounts::lens.account.perception",
          "sentiment_score|...|Gola::lens.account.perception",
          "sentiment_score|...|Anthropologie::lens.account.perception",
          "sentiment_score|...|Free People::lens.account.perception",
          "sentiment_score|...|Department stores::lens.account.perception",
        ],
        findingsException: null, findingsGroup: null,
        synthesized: true, synthesizing: false, status: "live", source: "curated",
      },
    ];
  }

  // Membership: which sections "contain" a finding (direct, grouped, or exception).
  function sectionsWith(sections, fid) {
    return sections.filter(function (s) {
      return (s.findings || []).indexOf(fid) >= 0
        || (s.findingsGroup && s.findingsGroup.ids.indexOf(fid) >= 0)
        || (s.findingsException && s.findingsException.id === fid);
    });
  }

  var ACCENTS = ["var(--chart-green)", "var(--chart-purple)", "var(--chart-yellow)", "var(--chart-red)", "var(--chart-gray)", "var(--base-blue-main)"];

  window.CURATION = {
    CONSISTENT_GROUP: CONSISTENT_GROUP,
    SYNTH: SYNTH,
    synthesize: synthesize,
    seedSections: seedSections,
    sectionsWith: sectionsWith,
    ACCENTS: ACCENTS,
  };
})();
