/* global React */
// =========================================================
// Gola Evidence Loop — data + shared pin store
// Evidence numbers verified against study.json / insights-v4.
// window.GOLA = { OBJECTIVES, FAMILIES, EVIDENCE, surfaceStructure }
// window.PinContext = React context for the Raw ⇄ Insights loop
// =========================================================

const OBJECTIVES = [
  { id: 1, short: "Sentiment & reach",
    text: "Understand sentiment and incremental reach for products within the OR." },
  { id: 2, short: "Sell-in & line planning",
    text: "Inform key account sell-in and line planning for Spring '28." },
  { id: 3, short: "Design feedback",
    text: "Capture design feedback on color, print, and pattern across core franchises." },
  { id: 4, short: "Perception by account",
    text: "Read perception across Anthropologie, Free People, Department-store, and Gola consumers." },
];

const FAMILIES = [
  { key: "cross",     glyph: "⇄", title: "Cross-franchise comparison", sub: "Top & bottom SMUs across the whole OR" },
  { key: "franchise", glyph: "⌗", title: "Product franchise drill-down", sub: "Variant spread inside each silhouette" },
  { key: "buyer",     glyph: "◑", title: "Segment cuts", sub: "New vs existing, retailer & brand-aware shoppers" },
  { key: "segment",   glyph: "◔", title: "Demographical cuts", sub: "Age, gender & behavioral lenses" },
];

// ---- Evidence cards ----
const EVIDENCE = [
  // ---------- CROSS-FRANCHISE ----------
  { id: "EV-C1", fam: "cross", objs: [1, 2],
    title: "Top SMUs across the line — sentiment score",
    q: "P1 1–5 average mapped to a 0–100 sentiment score",
    metric: { val: "72", label: "Hawk Twill leads the 35-SMU rotation" },
    n: 785, unit: "score",
    bars: [
      { label: "Hawk Twill", val: 72.1, hi: true },
      { label: "Championship", val: 67.6, hi: true },
      { label: "Sprinter Reflect", val: 67.0 },
      { label: "Delta Tonal", val: 66.8 },
      { label: "Elan", val: 63.4 },
    ] },
  { id: "EV-C2", fam: "cross", objs: [1, 2],
    title: "Bottom SMUs — where the line loses",
    q: "Sentiment score (0–100) · lowest-rated variants",
    metric: { val: "36", label: "Clora Mule sits at the floor" },
    n: 785, unit: "score",
    bars: [
      { label: "Badminton Ballerina", val: 47.1 },
      { label: "Elan Quilt Mule", val: 44.6 },
      { label: "Celestra Quilt", val: 43.0, low: true },
      { label: "Trakstar Flex", val: 42.9, low: true },
      { label: "Clora Mule", val: 35.8, low: true },
    ] },
  { id: "EV-C3", fam: "cross", objs: [2, 4],
    title: "The leader's sentiment is stable across all three accounts",
    q: "Sentiment score × Q2 retailer · Hawk Twill by account",
    metric: { val: "±4pt", label: "max account spread on the leader" },
    n: 352, unit: "score",
    bars: [
      { label: "Anthropologie", val: 77.4, hi: true },
      { label: "Free People", val: 75.6, hi: true },
      { label: "Dept store", val: 73.3 },
    ] },
  { id: "EV-C4", fam: "cross", objs: [2, 3],
    title: "Franchise sentiment ranking — cross-franchise read",
    q: "Sentiment score pooled across every variant in each franchise",
    metric: { val: "64.3", label: "Championship leads; Clora trails" },
    n: 785, unit: "score",
    bars: [
      { label: "Championship", val: 64.3, hi: true },
      { label: "Hawk", val: 63.3, hi: true },
      { label: "Delta", val: 63.1 },
      { label: "Sprinter", val: 58.8 },
      { label: "Amera", val: 56.9 },
      { label: "Elan", val: 55.8 },
      { label: "Clora", val: 35.8, low: true },
    ] },

  // ---------- FRANCHISE DRILL-DOWN ----------
  { id: "EV-F1", fam: "franchise", objs: [2, 3],
    title: "Hawk — same silhouette, 19-point sentiment swing",
    q: "Sentiment score · Hawk franchise variants",
    metric: { val: "19.2pt", label: "Twill upper vs standard — widest in the line" },
    n: 649, unit: "score",
    bars: [
      { label: "Hawk Twill", val: 72.1, hi: true },
      { label: "Hawk", val: 52.9, low: true },
    ] },
  { id: "EV-F2", fam: "franchise", objs: [2, 3],
    title: "Sprinter — five variants, 19-point spread",
    q: "Sentiment score · Sprinter franchise variants",
    metric: { val: "18.8pt", label: "Reflect leads; Outdoor is the drag" },
    n: 2079, unit: "score",
    bars: [
      { label: "Sprinter Reflect", val: 67.0, hi: true },
      { label: "Sprinter Tonal", val: 62.5 },
      { label: "Sprinter Satin", val: 61.0 },
      { label: "Sprinter Quilt", val: 59.3 },
      { label: "Sprinter Outdoor", val: 48.2, low: true },
    ] },
  { id: "EV-F3", fam: "franchise", objs: [2, 3],
    title: "Amera — Mesh is the outlier",
    q: "Sentiment score · Amera franchise variants",
    metric: { val: "11.7pt", label: "Mesh treatment drags an even silhouette" },
    n: 1691, unit: "score",
    bars: [
      { label: "Amera Satin", val: 63.0, hi: true },
      { label: "Amera Quilt", val: 61.3 },
      { label: "Amera", val: 61.1 },
      { label: "Amera Mesh", val: 51.3, low: true },
    ] },
  { id: "EV-F4", fam: "franchise", objs: [2, 3],
    title: "Elan — standard up, quilt mule down",
    q: "Sentiment score · Elan franchise variants",
    metric: { val: "18.8pt", label: "Materialization repeats the pattern" },
    n: 2333, unit: "score",
    bars: [
      { label: "Elan", val: 63.4, hi: true },
      { label: "Elan Satin", val: 62.0 },
      { label: "Elan Strap Quilt", val: 54.1 },
      { label: "Elan Quilt Mule", val: 44.6, low: true },
    ] },

  // ---------- BUYER CUTS ----------
  { id: "EV-B1", fam: "buyer", objs: [1, 4],
    title: "Aspirational shoppers lift the same top-five SMUs",
    q: "Sentiment score · aspirational segment vs overall · point lift",
    metric: { val: "+1–4", label: "sentiment lift on the identical top-five" },
    n: 428, unit: "pts",
    bars: [
      { label: "Hawk Twill", val: 3.5, hi: true },
      { label: "Championship", val: 3.0, hi: true },
      { label: "Elan", val: 2.2 },
      { label: "Sprinter Reflect", val: 1.4 },
      { label: "Delta Tonal", val: 0.9 },
    ] },
  { id: "EV-B2", fam: "buyer", objs: [4],
    title: "Aspirational retailer overlap = 54.5% of the sample",
    q: "Q2 · retailers shopped past 12 months · respondent count",
    metric: { val: "428", label: "shopped Anthro / Free People / Madewell" },
    n: 785, unit: "n",
    bars: [
      { label: "Dept store", val: 373, hi: true },
      { label: "Free People", val: 270 },
      { label: "Anthropologie", val: 206 },
      { label: "Madewell", val: 141 },
    ] },
  { id: "EV-B3", fam: "buyer", objs: [1, 3],
    title: "59% buy for design or new style — not replacement",
    q: "Q6 · main reason for last lifestyle-sneaker purchase · single-select",
    metric: { val: "59.5%", label: "design + new style vs 15.8% replacement" },
    n: 785, unit: "%",
    bars: [
      { label: "Liked the design", val: 33.9, hi: true },
      { label: "Add a new style", val: 25.6, hi: true },
      { label: "Replace older pair", val: 15.8 },
      { label: "Good value", val: 15.5 },
      { label: "Specific occasion", val: 9.2 },
    ] },
  { id: "EV-B4", fam: "buyer", objs: [4],
    title: "What Gola is currently associated with",
    q: "Q15 · single-select category association for Gola footwear",
    metric: { val: "21%", label: "“not familiar” — association is thin" },
    n: 785, unit: "%",
    bars: [
      { label: "Fashion sneakers", val: 21.3, hi: true },
      { label: "Not familiar", val: 21.0 },
      { label: "Casual everyday", val: 20.3 },
      { label: "Retro / lifestyle", val: 15.2 },
      { label: "Performance", val: 13.6, low: true },
    ] },

  // ---------- SEGMENT CUTS ----------
  { id: "EV-S1", fam: "segment", objs: [1, 3],
    title: "Design-led buying over-indexes among F18–34",
    q: "Q6 × age/gender · “liked the design” share",
    metric: { val: "36.2%", label: "F18–34 vs 31.4% F35+ vs 28.0% other" },
    n: 785, unit: "%",
    bars: [
      { label: "Female 18–34", val: 36.2, hi: true },
      { label: "Female 35+", val: 31.4 },
      { label: "Other", val: 28.0 },
    ] },
  { id: "EV-S2", fam: "segment", objs: [1],
    title: "80% wear lifestyle sneakers daily or weekly",
    q: "Q5 · wear frequency · single-select",
    metric: { val: "79.7%", label: "every day + a few times a week" },
    n: 785, unit: "%",
    bars: [
      { label: "Every day", val: 40.0, hi: true },
      { label: "Few times / week", val: 39.7, hi: true },
      { label: "Occasionally", val: 20.3 },
    ] },
  { id: "EV-S3", fam: "segment", objs: [1],
    title: "82% own three or more pairs",
    q: "Q4 · pairs currently owned · single-select",
    metric: { val: "82.5%", label: "wardrobe behavior, not single-pair utility" },
    n: 785, unit: "%",
    bars: [
      { label: "6+ pairs", val: 43.3, hi: true },
      { label: "3–5 pairs", val: 39.2, hi: true },
      { label: "1–2 pairs", val: 17.5 },
    ] },
  { id: "EV-S4", fam: "segment", objs: [4],
    title: "Performance permission vs activation — a 72-point gap",
    q: "Q17 credibility vs Q15 association vs Q16 consideration",
    metric: { val: "72pt", label: "credible (86%) minus associated (14%)" },
    n: 785, unit: "%",
    bars: [
      { label: "Credible (Q17)", val: 85.5, hi: true },
      { label: "Would consider (Q16)", val: 32.0 },
      { label: "Associate now (Q15)", val: 13.6, low: true },
    ] },
];

const EV_INDEX = {};
EVIDENCE.forEach((e) => { EV_INDEX[e.id] = e; });

// ---- Data significance per evidence card (3 tiers) ----
// high = large base + clear separation; mid = directional; low = thin/soft.
const SIGNIFICANCE = {
  "EV-C1": "high", "EV-C2": "mid", "EV-C3": "high", "EV-C4": "high",
  "EV-F1": "high", "EV-F2": "mid", "EV-F3": "mid", "EV-F4": "high",
  "EV-B1": "mid", "EV-B2": "high", "EV-B3": "high", "EV-B4": "low",
  "EV-S1": "low", "EV-S2": "high", "EV-S3": "high", "EV-S4": "high",
};
const SIG_META = {
  high: { label: "High significance", short: "High", tip: "large base size and a clear, separated pattern — safe to lead with." },
  mid: { label: "Moderate significance", short: "Moderate", tip: "directional; the pattern holds but the gap or base is smaller." },
  low: { label: "Low significance", short: "Low", tip: "thin base or soft separation — treat as a signal to probe, not a conclusion." },
};
function evSig(id) { return SIGNIFICANCE[id] || "mid"; }

// ---- Five curated insight callouts (from V4) — the Insights tab default ----
// Each links to the EV-* evidence cards that support it.
const INSIGHTS = [
  { id: "i1", num: "01", objs: [1, 2], confidence: 4, nav: "Three retailers, one answer",
    title: "Three retailers, one answer — the consumer has already pre-edited the line",
    tagline: "Hawk Twill, Championship, Sprinter Reflect, Delta Tonal and Elan rank top-five on every account cut. The buy isn't product selection — it's the edit around an already-decided core.",
    ev: ["EV-C1", "EV-C3"],
    action: "Lead Spring '28 sell-in with the same five-SMU core in every account deck. Treat the remaining slots as the editable surface.",
    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",
    ] },
  { id: "i2", num: "02", objs: [2, 3], confidence: 4, nav: "Materialization is the lever",
    title: "Two same-silhouette shoes, ~19 points apart — materialization is the lever, not silhouette",
    tagline: "Within-franchise sentiment spreads of 12–19 points across Hawk, Sprinter, Amera and Elan prove the line's variance lives one layer below silhouette — in the upper and material.",
    ev: ["EV-F1", "EV-F2", "EV-F3", "EV-F4"],
    action: "Brief Spring '28 development on materialization, not silhouette extensions. The same last in twill beats the same last in mesh.",
    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, not a single make-up — no treatment rescues the quilt.",
    } },
  { id: "i3", num: "03", objs: [1, 3], confidence: 4, nav: "Wardrobe, not utility",
    title: "Only 16% buy to replace — this is wardrobe behavior, not utility behavior",
    tagline: "59% buy for design or a new style; 82% own three or more pairs; 80% wear them daily or weekly. Premium SMU pricing is supported by category behavior, not durability.",
    ev: ["EV-B3", "EV-S3", "EV-S2"],
    action: "Brief comms + merch on wardrobe-building, not durability or replacement cycles. The premium price ladder is defensible on category behavior alone.",
    findingsNote: "No live findings in this batch carry purchase-motivation, wear-frequency or pairs-owned data — this insight stands on the pinned survey evidence above." },
  { id: "i4", num: "04", objs: [4, 2], confidence: 3, nav: "Unactivated permission",
    title: "Performance is permission Gola hasn't activated — the 72-point gap is internal, not external",
    tagline: "86% rate Gola credible in performance/athletic; only 14% currently associate the brand with that category. Consumers grant the permission long before the brand commits to playing.",
    ev: ["EV-S4", "EV-B4"],
    action: "Sequence performance as a future-state lab, not a near-term SKU push — start from the easiest category bridge and let the credibility carry it.",
    findingsNote: "No live findings in this batch carry performance-credibility or category-association data — this insight stands on the pinned survey evidence above. (The live set does show Gola at 20% consideration vs. Nike 70%, an adjacent awareness-gap signal in the Findings tab.)" },
  { id: "i5", num: "05", objs: [1, 4], confidence: 4, nav: "Aspirational = existing minus shelf",
    title: "The aspirational consumer is the existing consumer minus shelf — not a different design target",
    tagline: "The aspirational segment (54.5% of the sample) produces a top-five identical to overall, with a +1–4 point sentiment lift on the same SMUs. The lift is shelf presence, not different product.",
    ev: ["EV-B1", "EV-B2", "EV-C1"],
    action: "Stop briefing 'aspirational' as a different design audience. Invest in placement and visual merch at the three premium retailers; the product is already ready.",
    findings: [
      "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",
      "sentiment_score|...|>=55::lens.seg.consumer",
      "sentiment_score|...|Small boutiques::lens.gap.channel",
      "sentiment_score|...|Gola::lens.gap.channel",
    ],
    findingsGroup: {
      label: "Consistent across segments",
      sub: "20 segment, retailer & age cuts hold the same consideration pattern (ES 0.06–0.11) — evidence the aspirational shopper isn't a different design target",
      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",
      ],
    } },
];

// ---- Curated story structure (the tecovas hierarchy) ----
// Surfaced by AI from pinned evidence. Each evidence ref is checked
// against the pinned set so the UI can show pinned vs AI-pulled-in.
const STORIES = [
  { objId: 2,
    headline: "Lead Spring '28 sell-in with a decided five-SMU core; materialization is the editable lever, not silhouette.",
    resolution: "The buy is already pre-edited by the consumer. Hawk Twill, Championship, Sprinter Reflect, Delta Tonal and Elan top every account cut. Within franchises the variance lives one layer below silhouette — upper and material treatment move the sentiment score 12–19 points.",
    args: [
      { id: "A1", summary: "Five SMUs top the line on every account cut — the core is already decided.",
        findings: [
          { id: "F1", text: "Hawk Twill leads at a 72 sentiment score; the same five clear the top tier overall.", ev: ["EV-C1"] },
          { id: "F2", text: "The top-five order is stable across Anthropologie, Free People and Department-store shoppers.", ev: ["EV-C3"] },
        ] },
      { id: "A2", summary: "Within-franchise spreads of 12–19 points prove the line's variance is materialization, not silhouette.",
        findings: [
          { id: "F3", text: "Hawk's twill upper beats the standard Hawk by 19 sentiment points on an identical last.", ev: ["EV-F1"] },
          { id: "F4", text: "The pattern repeats across Sprinter, Amera and Elan — mesh and heavy quilt are the consistent drag.", ev: ["EV-F2", "EV-F3", "EV-F4", "EV-C2"] },
        ] },
    ] },
  { objId: 1,
    headline: "The line earns its reach on design-led demand, and the strongest SMUs carry that demand.",
    resolution: "59% buy for design or a new style; 80% wear daily; 82% own 3+ pairs. Premium SMU pricing is supported by category behavior, not durability. The aspirational shopper is the same demand curve in a different aisle.",
    args: [
      { id: "A1", summary: "Demand is wardrobe behavior, not replacement utility.",
        findings: [
          { id: "F1", text: "Design and new-style reasons total 59.5% of last purchases; replacement is only 15.8%.", ev: ["EV-B3"] },
          { id: "F2", text: "80% wear lifestyle sneakers daily or weekly and 82% own three or more pairs.", ev: ["EV-S2", "EV-S3"] },
        ] },
      { id: "A2", summary: "The aspirational shopper lifts the same SMUs, not different ones.",
        findings: [
          { id: "F3", text: "Aspirational shoppers lift the identical top-five by +1 to +4 sentiment points.", ev: ["EV-B1", "EV-C1"] },
        ] },
    ] },
  { objId: 3,
    headline: "Design variance is materialization-driven: the same last wins or loses on its upper.",
    resolution: "Across Hawk, Sprinter, Amera and Elan, fabric and upper treatment swing the sentiment score 12–19 points on an identical silhouette. Mesh and heavy-quilt treatments are the consistent drag; design-led buyers raise the stakes on getting materialization right.",
    args: [
      { id: "A1", summary: "Materialization moves sentiment more than silhouette across every core franchise.",
        findings: [
          { id: "F1", text: "Each franchise shows a 12–19 point sentiment spread driven by upper treatment.", ev: ["EV-F1", "EV-F2", "EV-F3", "EV-F4"] },
        ] },
      { id: "A2", summary: "Design-led buyers over-index, so materialization errors cost more.",
        findings: [
          { id: "F2", text: "Design is the #1 purchase reason and over-indexes among F18–34.", ev: ["EV-B3", "EV-S1"] },
        ] },
    ] },
  { objId: 4,
    headline: "Perception is consistent across accounts; Gola's unactivated permission is the whitespace.",
    resolution: "The top-five reads identically across Anthropologie, Free People and Department-store shoppers — perception isn't fragmented by account. Gola holds 86% performance credibility against only 14% current association: a 72-point gap of unactivated permission.",
    args: [
      { id: "A1", summary: "Account cuts agree on the product — there is one consumer, not four.",
        findings: [
          { id: "F1", text: "The leader's sentiment score varies about 4 points across the three premium accounts.", ev: ["EV-C3"] },
          { id: "F2", text: "The aspirational retailer union is 54.5% of the sample, overlapping heavily.", ev: ["EV-B2"] },
        ] },
      { id: "A2", summary: "Gola's granted permission outruns its current association.",
        findings: [
          { id: "F3", text: "86% find Gola credible in performance; only 14% associate it there today.", ev: ["EV-S4"] },
          { id: "F4", text: "21% are “not familiar” with Gola footwear — association is thin, not negative.", ev: ["EV-B4"] },
        ] },
    ] },
];

// Given a Set of pinned evidence ids, return the stories that have at least
// one pinned card, annotating each evidence ref as pinned or AI-pulled-in.
function surfaceStructure(pinnedSet) {
  return STORIES
    .map((story) => {
      let pinnedHits = 0;
      const args = story.args.map((a) => ({
        ...a,
        findings: a.findings.map((f) => ({
          ...f,
          ev: f.ev.map((id) => {
            const pinned = pinnedSet.has(id);
            if (pinned) pinnedHits++;
            return { id, pinned, card: EV_INDEX[id] };
          }),
        })),
      }));
      return { ...story, args, pinnedHits, obj: OBJECTIVES.find((o) => o.id === story.objId) };
    })
    .filter((s) => s.pinnedHits > 0);
}

window.GOLA = { OBJECTIVES, FAMILIES, EVIDENCE, EV_INDEX, STORIES, INSIGHTS, SIGNIFICANCE, SIG_META, evSig, surfaceStructure };

// ---- Shared pin store (React context) ----
window.PinContext = React.createContext(null);
