/* global React, Eyebrow, Chip */

// =========================================================
// Context tab — pre-flight studio for the upfront brief
// Research goals are the gospel; everything else is AI-drafted
// from the source materials.
//
// Subject: Gola Women's Sneaker Lab (survey 69f4f3be…c9ce, n=785).
// All scope, hypotheses, cuts and arcs are authored to ladder
// into the downstream Raw Results, Findings and Insights tabs.
// =========================================================

// ----- Gola Women's Sneaker Lab -----
const CTX_FOUNDATIONAL = {
  reader: "Brand + Line Planning leads (operational) + Design lead (strategic)",
  useCase: "Key-account sell-in + design iteration",
  leadNarrative: "Sell-in + design feedback",
  deckLength: "25–35 slides",
  save: "Notion intake + Desktop"
};

const CTX_SOURCES = [
{ id: "intake", type: "Notion intake", label: "Gola Women's Sneaker Lab", meta: "1 page · 11 fields", state: "ingested" },
{ id: "call1", type: "Call transcript", label: "Feb 24 — Gola Kickoff Sync", meta: "41 turns · 5 verbatims surfaced", state: "ingested" },
{ id: "call2", type: "Call transcript", label: "Mar 10 — OR & Audience Sync", meta: "33 turns · 3 verbatims · 2 late cuts added", state: "ingested" },
{ id: "email", type: "Email thread", label: "Feb 19 – Mar 27 · 11 messages", meta: "Sorted oldest-first · OR locked at 35 SMUs", state: "ingested" },
{ id: "questn", type: "Questionnaire", label: "v2 (.docx) — Q1 through P3", meta: "20 profile Qs + 3 product Qs", state: "ingested" }];


const CTX_PRIOR_STUDIES = [
{ id: "p1", name: "Gola Footwear Brand Tracker · 2025", date: "Oct 2025", type: "Tracker", rel: "Same account · prior brand read", linked: true,
  note: "Established Gola's thin category association — heavy 'not familiar' base going in. Anchors the awareness-gap framing." },
{ id: "p2", name: "Gola Men's Lifestyle Lab · 2025", date: "Aug 2025", type: "Custom lab", rel: "Same brand · adjacent methodology", linked: true,
  note: "Same SMU-rating method (P1 1–5 → sentiment score). Materialization-over-silhouette pattern first observed here." },
{ id: "p3", name: "Premium Women's Footwear Tracker · 2026 Q1", date: "Feb 2026", type: "Tracker", rel: "Cross-brand panel · price ladder", linked: false,
  note: "Auto-suggested — overlapping aspirational-retailer segment (Anthropologie / Free People / Madewell)." },
{ id: "p4", name: "Aspirational Retailer Shopper Study · 2025", date: "May 2025", type: "Custom lab", rel: "Channel read · same account targets", linked: false,
  note: "Auto-suggested — same Anthropologie / Free People shopper definition used for the account cuts." }];


const CTX_SECTIONS = [
{ id: "s1", num: "01", title: "Project Identity & Scope", icon: "ti-clipboard-text", confidence: 95, status: "confirmed" },
{ id: "s2", num: "02", title: "Business Situation Narrative", icon: "ti-file-text", confidence: 90, status: "in-review" },
{ id: "s4", num: "03", title: "Hypotheses & Sensitivities", icon: "ti-bulb", confidence: 85, status: "in-review" },
{ id: "s5", num: "04", title: "Audience", icon: "ti-users", confidence: 95, status: "confirmed" },
{ id: "s6", num: "05", title: "Questionnaire Story Map", icon: "ti-map-2", confidence: 90, status: "in-review" }];
window.CTX_SECTIONS = CTX_SECTIONS;

// Full switchable tab set for the context header bar. Research goals, project
// identity & scope and the business narrative are merged into one "Brief" tab
// (goals lead the UX); products in scope is its own panel; the remaining
// analytic sections stay standalone.
const CTX_TABS = [
{ id: "brief", title: "Research goals", icon: "ti-target-arrow" },
{ id: "products", title: "Product set", icon: "ti-shirt" },
...["s5", "s4", "s6"].map((id) => CTX_SECTIONS.find((s) => s.id === id))];
window.CTX_TABS = CTX_TABS;

// Scope facts authored once, surfaced in Project scope and copied into the
// Critical Cuts, Products and Questionnaire tabs.
const CTX_SCOPE = {
  audience: "785 women · US · ages 18–55+ · mix of Anthropologie, Free People, department-store, and Gola-aware shoppers",
  geography: "US only",
  criticalCuts: "4 account / perception segments — Anthropologie (n 206), Free People (n 270), Department-store (n 373), Gola consumers (n 159) — read alongside age, gender, brand affinity & channel",
  productSet: "35 SMUs from the FW26 OR · 8 franchises (Hawk, Delta, Sprinter, Amera, Viper, Elan, Trakstar, Celestra) + standalone styles (Championship, Championship Suede, Badminton Ballerina, Clora Mule) · each respondent rated ~15 · per-SMU base ≈ 286–352",
  questionnaire: "20 profile questions (Q1–Q20) + 3 product questions (P1 rating, P2 / P3 open-text)",
};

// Products in scope — 35 real SMUs (study.json), grouped by franchise.
const CTX_PRODUCTS = [
{ name: "Hawk", fr: "Hawk" },
{ name: "Hawk Twill", fr: "Hawk" },
{ name: "Delta", fr: "Delta" },
{ name: "Delta", fr: "Delta" },
{ name: "Delta Tonal", fr: "Delta" },
{ name: "Sprinter Quilt", fr: "Sprinter" },
{ name: "Sprinter Outdoor", fr: "Sprinter" },
{ name: "Sprinter Satin", fr: "Sprinter" },
{ name: "Sprinter Tonal", fr: "Sprinter" },
{ name: "Sprinter Reflect", fr: "Sprinter" },
{ name: "Sprinter Reflect", fr: "Sprinter" },
{ name: "Amera", fr: "Amera" },
{ name: "Amera Mesh", fr: "Amera" },
{ name: "Amera Mesh", fr: "Amera" },
{ name: "Amera Quilt", fr: "Amera" },
{ name: "Amera Satin", fr: "Amera" },
{ name: "Viper Nubuck", fr: "Viper" },
{ name: "Viper Nubuck", fr: "Viper" },
{ name: "Viper Nubuck", fr: "Viper" },
{ name: "Elan", fr: "Elan" },
{ name: "Elan", fr: "Elan" },
{ name: "Elan", fr: "Elan" },
{ name: "Elan", fr: "Elan" },
{ name: "Elan Satin", fr: "Elan" },
{ name: "Elan Quilt Mule", fr: "Elan" },
{ name: "Elan Strap Quilt", fr: "Elan" },
{ name: "Trakstar", fr: "Trakstar" },
{ name: "Trakstar Flex", fr: "Trakstar" },
{ name: "Celestra Quilt", fr: "Celestra" },
{ name: "Celestra Quilt", fr: "Celestra" },
{ name: "Celestra Quilt", fr: "Celestra" },
{ name: "Championship", fr: "Standalone" },
{ name: "Championship Suede", fr: "Standalone" },
{ name: "Badminton Ballerina", fr: "Standalone" },
{ name: "Clora Mule", fr: "Standalone" }].
map((p, i) => ({ ...p, id: "smu" + i }));


const CTX_HYPOTHESES = [
{ id: "H1", text: "Within a franchise, material and print treatment moves purchase consideration more than the silhouette — the same last wins or loses on its upper.",
  source: "Feb 24 call · Design lead: ‘it's the make-up, not the shape’", q: "P1 by franchise / colorway", pri: "headline" },
{ id: "H2", text: "A small hero core will top consideration consistently across all key accounts — perception isn't fragmented by retailer.",
  source: "Feb 24 call · Line planning lead", q: "P1 × Q2", pri: "core" },
{ id: "H3", text: "The aspirational (Anthropologie / Free People) shopper is the same demand curve as the existing Gola consumer — separated by shelf, not by product.",
  source: "Mar 10 call · added late", q: "Q2 / Q1 affinity", pri: "core", late: true },
{ id: "H4", text: "Demand is design-led and wardrobe-driven, not replacement — buyers add styles rather than replace pairs, which supports premium SMU pricing.",
  source: "Feb 24 call · Brand lead: ‘they don't wear them out, they collect them’", q: "Q6 / Q4 / Q5", pri: "core" },
{ id: "H5", text: "Bold / standout color and unique styling over-index among younger female shoppers (F18–34) versus the 35+ cut.",
  source: "Mar 10 call · added late", q: "Q9 / Q13 / Q14 × age", pri: "supporting", late: true },
{ id: "H6", text: "Gola holds latent performance credibility it hasn't activated — credibility outruns current category association.",
  source: "Notion intake · ‘whitespace in performance’", q: "Q15 / Q16 / Q17", pri: "supporting", framing: "opportunity" },
{ id: "H7", text: "Gola will index low on aided consideration versus mainstream peers but show meaningful openness among niche-affinity shoppers.",
  source: "Oct 2025 Brand Tracker · ‘heritage challenger’", q: "Q1", pri: "supporting", framing: "opportunity" }];


const CTX_SENSITIVITIES = [
{ kind: "framing", text: "Gola is a heritage challenger building share — low consideration vs. Nike/Adidas is framed as headroom and whitespace, not failure." },
{ kind: "method", text: "Each respondent rated ~15 of the 35 SMUs (rotated design); per-product base sizes vary. Show product n transparently in methodology." },
{ kind: "tone", text: "Department-store shoppers are the conservative read — use them as the sell-in baseline; Gola-affinity consumers are an enthusiast ceiling, not a forecast." },
{ kind: "language", text: "Lead with revealed preference — ‘the consumer has already pre-edited the line.’ Open-text design verbatims (P2 / P3) are still being synthesized at brief-time." }];


const CTX_ENTITIES = [
// client side — Gola franchises & SMUs in the OR
{ name: "Gola", kind: "client-brand", brand: "Gola" },
{ name: "Hawk", kind: "client-product", brand: "Gola" },
{ name: "Hawk Twill", kind: "client-product", brand: "Gola" },
{ name: "Championship", kind: "client-product", brand: "Gola" },
{ name: "Sprinter", kind: "client-product", brand: "Gola" },
{ name: "Delta", kind: "client-product", brand: "Gola" },
{ name: "Elan", kind: "client-product", brand: "Gola" },
{ name: "Amera", kind: "client-product", brand: "Gola" },
{ name: "Celestra", kind: "client-product", brand: "Gola" },
{ name: "Clora", kind: "client-product", brand: "Gola" },
{ name: "Trakstar", kind: "client-product", brand: "Gola" },
{ name: "Viper", kind: "client-product", brand: "Gola" },
{ name: "Badminton", kind: "client-product", brand: "Gola" },
// competitor brands in the Q1 affinity set — flagged
{ name: "Nike", kind: "competitor", brand: "Nike" },
{ name: "Adidas", kind: "competitor", brand: "Adidas" },
{ name: "New Balance", kind: "competitor", brand: "New Balance" },
{ name: "Vans", kind: "competitor", brand: "Vans" },
{ name: "Converse", kind: "competitor", brand: "Converse" },
{ name: "Puma", kind: "competitor", brand: "Puma" },
{ name: "Veja", kind: "competitor", brand: "Veja" },
{ name: "ALOHAS", kind: "competitor", brand: "ALOHAS" },
{ name: "Golden Goose", kind: "competitor", brand: "Golden Goose" },
{ name: "Sam Edelman", kind: "competitor", brand: "Sam Edelman" }];


const CTX_OPEN_QS = [
{ id: "oq1", q: "Which FW26 key-account meeting (Anthropologie, Free People, or Nordstrom) is driving the deck deadline?",
  aiDefault: "Anchor the sell-in narrative to the earliest of the three; treat that date as the hard deadline.", status: "pending" },
{ id: "oq2", q: "Should the deck lead with the hero-core sell-in story or the materialization design story?",
  aiDefault: "Lead the hero core (sell-in is time-sensitive); materialization as the ‘and how to edit it’ follow-on.", status: "pending" },
{ id: "oq3", q: "How prominent should the performance-permission whitespace be relative to the core lifestyle read?",
  aiDefault: "Position performance as a single forward-looking section, not a headline — the OR is lifestyle.", status: "confirmed" },
{ id: "oq4", q: "Use department-store shoppers as the default sell-in baseline in headlines, or blend with the warmer Gola-consumer read?",
  aiDefault: "Headline on the conservative department-store read; carry the Gola-consumer ceiling as a supporting band.", status: "pending" }];


const STORY_ARCS = [
{ id: "arc1", title: "The Hero Core", subtitle: "Deck's headline section", nodes: ["P1 cross-franchise", "Q2 account", "Five-SMU core"] },
{ id: "arc2", title: "Materialization is the Lever", subtitle: "Design narrative", nodes: ["P1 within-franchise", "P3 verbatims", "Design brief"] },
{ id: "arc3", title: "Wardrobe Demand", subtitle: "Price-ladder support", nodes: ["Q6", "Q4", "Q5"] },
{ id: "arc4", title: "The Sell-In Chain", subtitle: "For key accounts", nodes: ["Q2", "P1 by account", "Dept-store baseline"] },
{ id: "arc5", title: "Unactivated Permission", subtitle: "Brand opportunity", nodes: ["Q17", "Q15", "Q16"] }];


const TIER3_MODULATORS = ["Gender (Q19)", "Age (Q20)", "Retailer shopped (Q2)", "Sneaker brand affinity (Q1)", "Channel preference (Q3)"];

// =========================================================

function ResearchGoals() {
  const [goals, setGoals] = React.useState(() =>
  (window.RESEARCH_GOALS || []).map((t, i) => ({ id: "g" + i + "-" + Math.random().toString(36).slice(2, 6), text: t }))
  );
  const [overId, setOverId] = React.useState(null);
  const dragId = React.useRef(null);

  React.useEffect(() => {window.RESEARCH_GOALS = goals.map((g) => g.text);}, [goals]);

  function commit(id, text) {
    const t = text.replace(/\s+/g, " ").trim();
    setGoals((gs) => t === "" ? gs.filter((g) => g.id !== id) : gs.map((g) => g.id === id ? { ...g, text: t } : g));
  }
  function del(id) {setGoals((gs) => gs.filter((g) => g.id !== id));}
  function add() {
    const id = "g" + Date.now();
    setGoals((gs) => [...gs, { id, text: "" }]);
    setTimeout(() => {const el = document.querySelector('[data-goal="' + id + '"]');if (el) el.focus();}, 0);
  }
  function onDrop(e, overIdv) {
    e.preventDefault();
    const from = dragId.current;
    setOverId(null);
    dragId.current = null;
    if (!from || from === overIdv) return;
    setGoals((gs) => {
      const arr = gs.slice();
      const fi = arr.findIndex((g) => g.id === from);
      const ti = arr.findIndex((g) => g.id === overIdv);
      if (fi < 0 || ti < 0) return gs;
      const [m] = arr.splice(fi, 1);
      arr.splice(ti, 0, m);
      return arr;
    });
  }

  return (
    <div className="ctx__goals-list">
      {goals.map((g, i) =>
      <div
        key={g.id}
        className={"ctx-goal" + (overId === g.id ? " is-drop-target" : "")}
        onDragOver={(e) => e.preventDefault()}
        onDragEnter={() => {if (dragId.current && dragId.current !== g.id) setOverId(g.id);}}
        onDrop={(e) => onDrop(e, g.id)}>

          <span
          className="ctx-goal__grip"
          draggable
          onDragStart={(e) => {dragId.current = g.id;e.dataTransfer.effectAllowed = "move";}}
          onDragEnd={() => {dragId.current = null;setOverId(null);}}
          title="Drag to reorder">
            <i className="ti ti-grip-vertical"></i>
          </span>
          <span className="ctx-goal__num">{i + 1}.</span>
          <span
          className="ctx-goal__text"
          data-goal={g.id}
          contentEditable
          suppressContentEditableWarning
          spellCheck={false}
          onKeyDown={(e) => {if (e.key === "Enter") {e.preventDefault();e.currentTarget.blur();}}}
          onBlur={(e) => commit(g.id, e.currentTarget.textContent)}>
            {g.text}
          </span>
          <button className="ctx-goal__del" onClick={() => del(g.id)} title="Delete goal" aria-label="Delete goal">
            <i className="ti ti-trash"></i>
          </button>
        </div>
      )}
      <button className="ctx-goal__add" onClick={add}>
        <i className="ti ti-plus"></i>Add goal
      </button>
    </div>);

}

function ContextView() {
  const store = React.useContext(window.PinContext);
  const activeId = (store && store.ctxSection) || "brief";
  const setActiveId = (store && store.setCtxSection) || (() => {});
  const [objExpanded, setObjExpanded] = React.useState(true);
  const [showAddSource, setShowAddSource] = React.useState(true);
  const [panelOpen, setPanelOpen] = React.useState(false);
  const [linkedStudies, setLinkedStudies] = React.useState(() =>
  CTX_PRIOR_STUDIES.filter((p) => p.linked).map((p) => p.id)
  );

  function toggleLink(id) {
    setLinkedStudies((arr) => arr.includes(id) ? arr.filter((x) => x !== id) : [...arr, id]);
  }

  const active = CTX_SECTIONS.find((s) => s.id === activeId);

  return (
    <div className="ctx">
      {/* Brief — research goals (hero) + foundational identity & narrative */}
      {activeId === "brief" &&
      <>
        <article className="gl-ev gl-cc ctx__goals ctx__goals--hero">
          <div className="gl-cc__top">
            <div className="gl-cc__statement">Research goals</div>
          </div>
          <div className="ctx__goals-synth">
            <i className="ti ti-sparkles"></i>
            <span><strong>Synthesist</strong> · Every headline, section, and recommendation in Narrative + Insights is drafted to ladder back to one of these goals. Edit the goals here and re-generate downstream to re-anchor the whole deck.</span>
          </div>
          <ResearchGoals />
        </article>

        <div className="ctx-brief__divider">
          <span>Foundational context</span>
          <span className="ctx-brief__divider-meta">AI-drafted from source · supports the goals above</span>
        </div>

        <article className="gl-ev gl-cc ctx__brief-card">
          <div className="gl-cc__top"><div className="gl-cc__statement">Project scope</div></div>
          <Section1 />
        </article>
        <article className="gl-ev gl-cc ctx__brief-card">
          <div className="gl-cc__top"><div className="gl-cc__statement">Business narrative</div></div>
          <Section2 />
        </article>
      </>
      }

      {/* Products in scope — full-width line-sheet table */}
      {activeId === "products" && <ProductsCard bare />}

      {/* Active section canvas (standalone analytic sections) */}
      {active &&
      <div className="ctx__canvas">
        <SectionRenderer section={active} />
      </div>
      }

      {/* Files & sources drawer */}
      <div className={"ctx-drawer" + (panelOpen ? " is-open" : "")} role="dialog" aria-modal="true" aria-hidden={!panelOpen}>
        <div className="ctx-drawer__scrim" onClick={() => setPanelOpen(false)}></div>
        <aside className="ctx-drawer__panel">
          <div className="ctx-drawer__head">
            <div>
              <div className="ctx-drawer__title">Files &amp; sources</div>
              <div className="ctx-drawer__sub">Everything the Synthesist reads to draft this brief</div>
            </div>
            <button className="ctx-drawer__close" onClick={() => setPanelOpen(false)} aria-label="Close panel"><i className="ti ti-x"></i></button>
          </div>
          <div className="ctx-drawer__body">
            {/* Sources ledger */}
            <div className="ctx__sources">
              <div className="ctx__sources-head">
                <span style={{ fontFamily: "var(--ms-font-mono)", fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ms-fg-muted)" }}>Sources · {CTX_SOURCES.length}</span>
                <button className="ctx__add-source">+ Add source</button>
              </div>
              {showAddSource &&
              <div className="ctx__add-banner" style={{ marginTop: 0, marginBottom: 10 }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><i className="ti ti-sparkles" style={{ color: "var(--base-brand-green-main)" }}></i><span>Synthesist · <strong>Anything else to add before I synthesize?</strong> Other emails, internal Slack, prior decks?</span></span>
                  <div style={{ display: "inline-flex", gap: 6 }}>
                    <button className="studio__btn" style={{ fontSize: 12, padding: "4px 9px" }}>Add more</button>
                    <button className="studio__btn studio__btn--ghost" style={{ fontSize: 12, padding: "4px 9px" }} onClick={() => setShowAddSource(false)}>That's everything</button>
                  </div>
                </div>
              }
              <div className="ctx__sources-grid">
                {CTX_SOURCES.map((s) => <SourceCard key={s.id} src={s} />)}
              </div>
            </div>

            {/* Prior studies — link to give the AI cross-study memory */}
            <div className="ctx__priors">
              <div className="ctx__priors-head">
                <div>
                  <span style={{ fontFamily: "var(--ms-font-mono)", fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ms-fg-muted)" }}>
                    Linked prior studies · {linkedStudies.length} of {CTX_PRIOR_STUDIES.length}
                  </span>
                </div>
                <button className="ctx__add-source">+ Link a study</button>
              </div>
              <div className="ctx__priors-grid">
                {CTX_PRIOR_STUDIES.map((p) =>
                <PriorStudyCard key={p.id} study={p} linked={linkedStudies.includes(p.id)} onToggle={() => toggleLink(p.id)} />
                )}
              </div>
            </div>
          </div>
        </aside>
      </div>

    </div>);

}

function SourceCard({ src }) {
  const icon = src.type === "Notion intake" ? "ti-layout-board" : src.type === "Call transcript" ? "ti-player-play" : src.type === "Email thread" ? "ti-mail" : src.type === "Questionnaire" ? "ti-list-numbers" : "ti-plus";
  return (
    <div className="ctx-source">
      <div className="ctx-source__icon"><i className={"ti " + icon}></i></div>
      <div className="ctx-source__main">
        <div className="ctx-source__type">{src.type}</div>
        <div className="ctx-source__label">{src.label}</div>
        <div className="ctx-source__meta">{src.meta}</div>
      </div>
      <div className="ctx-source__state" title="Ingested"><i className="ti ti-circle-check-filled"></i></div>
    </div>);

}

function PriorStudyCard({ study, linked, onToggle }) {
  return (
    <div className={"ctx-prior" + (linked ? " is-linked" : " is-suggested")}>
      <div className="ctx-prior__head">
        <span className="ctx-prior__date">{study.date}</span>
      </div>
      <div className="ctx-prior__name">{study.name}</div>
      <div className="ctx-prior__rel">{study.rel}</div>
      <div className="ctx-prior__foot">
        {linked ?
        <span className="ctx-prior__badge ctx-prior__badge--linked">✓ Linked · feeds hypotheses</span> :
        <span className="ctx-prior__badge ctx-prior__badge--sugg">✦ Suggested</span>}
        <button className="ctx-prior__btn" onClick={onToggle}>
          {linked ? "Unlink" : "Link this study"}
        </button>
      </div>
    </div>);

}

function SectionRenderer({ section }) {
  if (!section) return null;
  switch (section.id) {
    case "s1":return <SectionShell section={section}><Section1 /></SectionShell>;
    case "s2":return <SectionShell section={section}><Section2 /></SectionShell>;
    case "s3":return <SectionShell section={section}><Section3 /></SectionShell>;
    case "s4":return <SectionShell section={section}><Section4 /></SectionShell>;
    case "s5":return <Section5 />;
    case "s6":return <SectionShell section={section}><Section6 /></SectionShell>;
    case "s7":return <SectionShell section={section}><Section7 /></SectionShell>;
    case "s10":return <SectionShell section={section}><Section10 /></SectionShell>;
    default:return <SectionShell section={section}><SectionPlaceholder section={section} /></SectionShell>;
  }
}

function SectionShell({ section, children }) {
  return (
    <section className="ctx-canvas">
      <div className="ctx-canvas__bar">
        <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
          <span className="studio__version-tag">
            <span className="dot"></span>
            Section {section.num} · {section.title}
          </span>
          <span className="ai-drafted-tag">
            <i className="ai-drafted-tag__star ti ti-sparkles"></i>
            AI-drafted · {section.status === "needs-input" ? "needs your input" : section.status === "confirmed" ? "confirmed" : "in review"}
          </span>
          <span style={{ fontSize: 12, fontFamily: "var(--ms-font-mono)", letterSpacing: "0.06em", color: "var(--ms-fg-muted)" }}>
            Confidence {section.confidence}%
          </span>
        </div>
        <div style={{ display: "inline-flex", gap: 6 }}>
          <button className="studio__btn studio__btn--ghost" style={{ fontSize: 12 }}>Re-draft from source</button>
          <button className="studio__btn studio__btn--primary" style={{ fontSize: 12 }}>Mark confirmed</button>
        </div>
      </div>
      <div className="ctx-canvas__body">{children}</div>
    </section>);

}

// ----- Section 1 — Identity & Scope -----
function Section1() {
  return (
    <div>
      <table className="ctx-table">
        <tbody>
          {[
          ["Business Unit", "Women's Lifestyle · Labs Custom"],
          ["Study type", "Product Sentiment + Brand Perception Lab"],
          ["Audience", CTX_SCOPE.audience],
          ["Geographies", CTX_SCOPE.geography],
          ["Critical cuts", CTX_SCOPE.criticalCuts],
          ["Product set", CTX_SCOPE.productSet],
          ["Questionnaire", CTX_SCOPE.questionnaire]].
          map(([k, v]) =>
          <tr key={k}>
              <td><span className="ctx-table__key">{k}</span></td>
              <td>{v}</td>
            </tr>
          )}
        </tbody>
      </table>
    </div>);

}

// ----- Section 2 — Business situation -----
function Section2() {
  return (
    <div>
      <p className="ctx-prose">
        Gola is a heritage British footwear brand rebuilding its women's lifestyle presence in the US. Going in, the brand reads as a niche challenger — strong heritage equity, but thin current category association. The lab tests the FW26 women's OR — 35 SMUs across eight franchises (Hawk, Delta, Sprinter, Amera, Viper, Elan, Trakstar and Celestra) plus the standalone styles Championship, Badminton and Clora Mule — against a US women's lifestyle audience. Each respondent rated ~15 of the 35, so per-SMU bases run ≈ 286–352.
      </p>
      <p className="ctx-prose">
        Note on the brand set: Nike, Adidas, New Balance, Vans, Converse, Puma, Veja, ALOHAS, Golden Goose and Sam Edelman appear in the Q1 affinity set as competitor / market brands, not Gola products. The only client products in the test are Gola's own franchise SMUs.
      </p>
      <p className="ctx-prose">
        The lab serves two distinct purposes simultaneously:
      </p>
      <ol style={{ paddingLeft: 22, color: "var(--ms-fg)", fontSize: 14, lineHeight: 1.6 }}>
        <li>Key-account sell-in &amp; line planning — for the FW26 buys at the aspirational accounts (Anthropologie, Free People) and the broader department-store channel.</li>
        <li>Design iteration tool — for ongoing concept refinement, particularly which colorways, prints and material treatments to carry forward inside each franchise.</li>
      </ol>
    </div>);

}

// ----- Section 3 — Stated objectives -----
function Section3() {
  return (
    <div>
      <div className="ctx-callout ctx-callout--locked">
        <div className="ctx-callout__label">Treat as gospel</div>
        <p style={{ margin: 0, fontSize: 12, color: "var(--ms-fg-muted)" }}>Verbatim from the upfront brief. The deck must answer these or the client will say it didn't.</p>
      </div>
      <div style={{ marginTop: 14 }}>
        <div style={{ fontFamily: "var(--ms-font-mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ms-fg-muted)", marginBottom: 8 }}>Research goals</div>
        <ol className="ctx-num-list">
          {(window.RESEARCH_GOALS || []).map((g, i) => <li key={i}>{g}</li>)}
        </ol>
      </div>
    </div>);

}

// ----- Section 4 — Hypotheses & Sensitivities (custom view) -----
function Section4() {
  return (
    <div>
      <div className="ctx-subhead">Hypotheses to test · 7</div>
      <div className="ctx-hyp-grid">
        {CTX_HYPOTHESES.map((h) => <HypothesisCard key={h.id} h={h} />)}
      </div>

      <div className="ctx-subhead" style={{ marginTop: 22 }}>Framing sensitivities · propagate to Narrative section editor</div>
      <div className="ctx-sens">
        {CTX_SENSITIVITIES.map((s, i) =>
        <div key={i} className={"ctx-sens__row ctx-sens__row--" + s.kind}>
            <span className="ctx-sens__pill">{s.kind}</span>
            <span>{s.text}</span>
          </div>
        )}
      </div>
    </div>);

}

function HypothesisCard({ h }) {
  return (
    <article className={"ctx-hyp ctx-hyp--" + h.pri}>
      <div className="ctx-hyp__head">
        <span className="ctx-hyp__id">{h.id}</span>
        <span className={"ctx-hyp__pri ctx-hyp__pri--" + h.pri}>{h.pri}</span>
        {h.late && <span className="ctx-hyp__late">★ Late addition</span>}
        {h.framing && <span className="ctx-hyp__framing">⚠ Opportunity framing</span>}
      </div>
      <div className="ctx-hyp__text">{h.text}</div>
      <div className="ctx-hyp__foot">
        <div className="ctx-hyp__src">
          <span className="ctx-hyp__src-label">Source</span>
          <span>{h.source}</span>
        </div>
        <div className="ctx-hyp__src">
          <span className="ctx-hyp__src-label">Diagnostic</span>
          <span className="ctx-hyp__diag">{h.q}</span>
        </div>
      </div>
      <div className="ctx-hyp__status">
        <span className="ctx-hyp__status-pill">Untested · awaiting analysis</span>
      </div>
    </article>);

}

// ----- Section 5 — Critical cuts (two cards, no draft bar) -----
function Section5() {
  return (
    <>
      <section className="ctx-canvas">
        <div className="gl-cc__top" style={{ marginBottom: 14 }}><div className="gl-cc__statement">Audience overview</div></div>
        <table className="ctx-table">
          <tbody>
            <tr><td><span className="ctx-table__key">Audience</span></td><td>{CTX_SCOPE.audience}</td></tr>
            <tr><td><span className="ctx-table__key">Geography</span></td><td>{CTX_SCOPE.geography}</td></tr>
            <tr><td><span className="ctx-table__key">Critical cuts</span></td><td>{CTX_SCOPE.criticalCuts}</td></tr>
          </tbody>
        </table>
      </section>

      <section className="ctx-canvas" style={{ marginTop: 16 }}>
        <div className="gl-cc__top" style={{ marginBottom: 14 }}><div className="gl-cc__statement">Consumer profiles</div></div>
        <div className="ctx-subhead">Demographic cuts · always run</div>
        <div className="ctx-cuts">
          {["Gender (Q19)", "Age 18-24 / 25-34 / 35-44 / 45-54 / 55+ (Q20)"].map((c) => <Chip key={c} kind="ghost">{c}</Chip>)}
        </div>

        <div className="ctx-subhead" style={{ marginTop: 18 }}>Behavioral cuts · always run</div>
        <div className="ctx-cuts">
          {["Pairs owned (Q4)", "Wear frequency (Q5)", "Purchase reason (Q6)", "Attribute priority (Q7)", "Channel preference (Q3)", "Full-price vs sale (Q12)"].map((c) => <Chip key={c} kind="ghost">{c}</Chip>)}
        </div>

        <div className="ctx-subhead" style={{ marginTop: 18 }}>Account &amp; perception cuts · sell-in + Goal 4</div>
        <div className="ctx-cuts">
          {["Anthropologie shoppers (Q2) ★ · n 206", "Free People shoppers (Q2) ★ · n 270", "Department-store shoppers (Q2) ★ baseline · n 373", "Gola consumers (Q1 affinity) ★ ceiling · n 159", "Retailer shopped (Q2)", "Expected retail (Q18)"].map((c) => <Chip key={c} kind="accent">{c}</Chip>)}
        </div>

        <div className="ctx-subhead" style={{ marginTop: 18 }}>Product / preference cuts · design narrative</div>
        <div className="ctx-cuts">
          {["Sneaker brand affinity (Q1) ★ headline", "Color palette (Q9)", "Silhouette preference (Q8)", "Style type (Q13)", "Uniqueness importance (Q14)", "Gola association (Q15)", "Performance credibility (Q17)"].map((c) => <Chip key={c} kind="accent">{c}</Chip>)}
        </div>
      </section>
    </>);

}

// ----- Section 6 — Story Map (custom view) -----
function Section6() {
  return (
    <div>
      <div className="ctx-subhead">Questionnaire</div>
      <p className="ctx-prose" style={{ marginTop: 6 }}>{CTX_SCOPE.questionnaire}</p>

      <div className="ctx-subhead" style={{ marginTop: 18 }}>Question tiers</div>
      <div className="ctx-tiers">
        <div className="ctx-tier ctx-tier--1">
          <div className="ctx-tier__label">Tier 1 · Headline</div>
          <div className="ctx-tier__chips">{["P1", "Q2", "Q1", "Q6"].map((q) => <span key={q}>{q}</span>)}</div>
        </div>
        <div className="ctx-tier ctx-tier--2">
          <div className="ctx-tier__label">Tier 2 · Supporting (2 late ★)</div>
          <div className="ctx-tier__chips">{["P2 / P3", "Q9 ★", "Q8", "Q13", "Q7", "Q15", "Q16", "Q17", "Q14 ★"].map((q) => <span key={q}>{q}</span>)}</div>
        </div>
        <div className="ctx-tier ctx-tier--3">
          <div className="ctx-tier__label">Tier 3 · Foundational lenses (always-on cuts)</div>
          <div className="ctx-tier__chips">{TIER3_MODULATORS.map((q) => <span key={q}>{q}</span>)}</div>
          <div className="ctx-tier__hint">↳ propagate to Raw Results as always-on filter chips</div>
        </div>
        <div className="ctx-tier ctx-tier--4">
          <div className="ctx-tier__label">Tier 4 · Background</div>
          <div className="ctx-tier__chips">{["Q4", "Q5", "Q10", "Q11", "Q12", "Q18"].map((q) => <span key={q}>{q}</span>)}</div>
        </div>
      </div>

      <div className="ctx-subhead" style={{ marginTop: 22 }}>Story arcs · sequenced as continuous arguments in the deck</div>
      <div className="ctx-arcs">
        {STORY_ARCS.map((a, i) => <ArcRow key={a.id} idx={i + 1} arc={a} />)}
      </div>
    </div>);

}

function ArcRow({ idx, arc }) {
  return (
    <div className="ctx-arc">
      <div className="ctx-arc__head">
        <span className="ctx-arc__idx">Arc {idx}</span>
        <span className="ctx-arc__title">{arc.title}</span>
        <span className="ctx-arc__sub">{arc.subtitle}</span>
      </div>
      <div className="ctx-arc__nodes">
        {arc.nodes.map((n, i) =>
        <React.Fragment key={i}>
            <span className="ctx-arc__node">{n}</span>
            {i < arc.nodes.length - 1 && <span className="ctx-arc__arrow">→</span>}
          </React.Fragment>
        )}
      </div>
    </div>);

}

// ----- Section 7 — Deck Outline v0 -----
function Section7() {
  const outline = [
  { num: "01", title: "Cover & Objectives", tier: "client-essential", slides: "1–2", direction: "Frame the deck as answering Gola's two-headed question: what sells in at the key accounts? what guides design iteration inside the franchises?" },
  { num: "02", title: "Methodology & Audience", tier: "client-essential", slides: "2–3", direction: "785 US women, 35-SMU rotated design (~15 rated each). Note per-product base sizes transparently." },
  { num: "03", title: "The Consumer We Studied", tier: "standard", slides: "3–4", direction: "Wardrobe-builder, design-led, multi-channel. Establish the aspirational-retailer overlap up front." },
  { num: "04", title: "The Hero Core — The Headline", tier: "headline", slides: "5–7", direction: "Five SMUs (Hawk Twill, Championship, Sprinter Reflect, Delta Tonal, Amera Satin) top every account cut. Deck's center of gravity." },
  { num: "05", title: "Materialization is the Lever", tier: "client-essential", slides: "4–5", direction: "Up to 22pt within-franchise swings on upper / material (Hawk Twill leads, plain Hawk trails). Mesh & heavy quilt are the drag; address the design brief directly." },
  { num: "06", title: "Wardrobe Demand & the Price Ladder", tier: "client-essential", slides: "3–4", direction: "59% buy for design / new style; 82% own 3+ pairs. Premium SMU pricing defended on category behavior, not durability." },
  { num: "07", title: "Account Perception & Sell-In Assortment", tier: "client-essential", slides: "5–7", direction: "Two views: perception by account + optimal assortment for each key account, on the department-store baseline." },
  { num: "08", title: "Brand Opportunity: Performance Permission", tier: "standard", slides: "2–3", direction: "86% credible vs 14% associated — the 72-pt unactivated gap. Frame as forward-looking whitespace, not a near-term push." },
  { num: "09", title: "Strategic Implications", tier: "client-essential", slides: "3–4", direction: "Two stacks: sell-in narrative for line planning, design iteration for the design lead." },
  { num: "10", title: "Appendix", tier: "standard", slides: "as needed", direction: "Full questionnaire, cross-tab tables, per-SMU product list." }];

  return (
    <div>
      <div className="ctx-subhead">10 sections · target 25–35 slides · seeds the Narrative tab</div>
      <div className="ctx-outline">
        {outline.map((o) =>
        <div key={o.num} className={"ctx-out ctx-out--" + (o.tier === "headline" ? "headline" : o.tier === "client-essential" ? "essential" : "standard")}>
            <div className="ctx-out__num">{o.num}</div>
            <div className="ctx-out__main">
              <div className="ctx-out__head">
                <span className="ctx-out__title">{o.title}</span>
                <span className={"ctx-out__tier ctx-out__tier--" + (o.tier === "headline" ? "headline" : o.tier === "client-essential" ? "essential" : "standard")}>
                  {o.tier === "headline" ? "★ HEADLINE" : o.tier === "client-essential" ? "client-essential" : "standard"}
                </span>
                <span className="ctx-out__slides">{o.slides} slides</span>
              </div>
              <div className="ctx-out__dir">{o.direction}</div>
            </div>
          </div>
        )}
      </div>
    </div>);

}

// ----- Section 10 — Open Questions -----
function Section10() {
  const [oqs, setOqs] = React.useState(CTX_OPEN_QS);
  function setStatus(id, status) {
    setOqs((arr) => arr.map((o) => o.id === id ? { ...o, status } : o));
  }
  return (
    <div>
      <div className="ctx-subhead">4 open questions · resolve before locking the brief</div>
      <div className="ctx-oqs">
        {oqs.map((oq) =>
        <div key={oq.id} className={"ctx-oq ctx-oq--" + oq.status}>
            <div className="ctx-oq__head">
              <span className="ctx-oq__id">{oq.id.toUpperCase()}</span>
              <span className={"ctx-oq__status ctx-oq__status--" + oq.status}>{oq.status === "confirmed" ? "✓ confirmed" : "awaiting answer"}</span>
            </div>
            <div className="ctx-oq__q">{oq.q}</div>
            <div className="ctx-oq__default">
              <span className="ctx-oq__default-label">✦ Default if no response</span>
              <span>{oq.aiDefault}</span>
            </div>
            <div className="ctx-oq__actions">
              <button className="studio__btn studio__btn--primary" style={{ fontSize: 12 }} onClick={() => setStatus(oq.id, "confirmed")}>Accept default</button>
              <button className="studio__btn" style={{ fontSize: 12 }}>Flip</button>
              <button className="studio__btn studio__btn--ghost" style={{ fontSize: 12 }}>Write your own…</button>
            </div>
          </div>
        )}
      </div>
    </div>);

}

// ----- Products in scope — line-sheet table -----
const PROD_COLS = [
{ key: "name", label: "Name", sort: true },
{ key: "desc", label: "Description", sort: true },
{ key: "section", label: "Survey Section", sort: true },
{ key: "price", label: "Price", sort: true },
{ key: "colorway", label: "Color way", sort: true },
{ key: "asset", label: "Asset format", sort: true },
{ key: "pattern", label: "Pattern", filter: true }];


function ProductsCard({ bare }) {
  const [rows, setRows] = React.useState(CTX_PRODUCTS);
  function del(id) {setRows((rs) => rs.filter((r) => r.id !== id));}

  const table = (
    <div className="ctx-ptable__scroll">
      <div className="ctx-ptable">
        {/* header */}
        <div className="ctx-ptable__head">
          <div className="ctx-ptable__count">{rows.length} Products</div>
          {PROD_COLS.map((c) =>
          <div key={c.key} className={"ctx-ptable__th ctx-pcol--" + c.key}>
              <span>{c.label}</span>
              {c.sort && <i className="ti ti-arrows-sort ctx-ptable__sorticon"></i>}
              {c.filter && <i className="ti ti-filter ctx-ptable__sorticon"></i>}
            </div>
          )}
          <div className="ctx-ptable__th ctx-pcol--del"></div>
        </div>

        {/* rows */}
        {rows.map((p) => <ProductRow key={p.id} p={p} onDelete={() => del(p.id)} />)}
      </div>
    </div>
  );

  const addBtn = <button className="ctx-prod__add"><i className="ti ti-plus"></i>Add product</button>;
  const meta = <span className="ctx__prod-meta">{rows.length} SMUs · 8 franchises · FW26 OR</span>;

  if (bare) {
    return (
      <section className="ctx__products-full">
        <div className="ctx__products-fullhead">
          <h2 className="ctx__products-title">Product set</h2>
          {meta}
        </div>
        <p className="ctx__products-desc">{CTX_SCOPE.productSet}</p>
        {table}
        {addBtn}
      </section>);

  }

  return (
    <article className="gl-ev gl-cc ctx__products">
      <div className="gl-cc__top">
        <div className="gl-cc__statement">Products in scope</div>
        {meta}
      </div>
      {table}
      {addBtn}
    </article>);

}

function ProductRow({ p, onDelete }) {
  return (
    <div className="ctx-ptable__row">
      <div className="ctx-pcell ctx-pcol--thumb">
        <div className="ctx-prod__thumb"><i className="ti ti-photo"></i></div>
      </div>
      <div className="ctx-pcell ctx-pcol--name">
        <input className="ctx-prod__input" defaultValue={p.name} aria-label="Product name" />
      </div>
      <div className="ctx-pcell ctx-pcol--desc">
        <button className="ctx-prod__addlink">Add description</button>
      </div>
      <div className="ctx-pcell ctx-pcol--section">
        <span className="ctx-prod__pill">Product questions</span>
        <button className="ctx-prod__caret" aria-label="Change section"><i className="ti ti-chevron-down"></i></button>
      </div>
      <div className="ctx-pcell ctx-pcol--price">
        <input className="ctx-prod__input" defaultValue="" placeholder="—" inputMode="numeric" aria-label="Price" />
      </div>
      <div className="ctx-pcell ctx-pcol--colorway">
        <input className="ctx-prod__input" defaultValue="" aria-label="Color way" />
      </div>
      <div className="ctx-pcell ctx-pcol--asset">
        <button className="ctx-prod__select"><span className="ctx-prod__select-ph">Select format</span><i className="ti ti-chevron-down"></i></button>
      </div>
      <div className="ctx-pcell ctx-pcol--pattern">
        <button className="ctx-prod__tags">Select tags<i className="ti ti-chevron-down"></i></button>
      </div>
      <div className="ctx-pcell ctx-pcol--del">
        <button className="ctx-prod__del" onClick={onDelete} aria-label="Remove product"><i className="ti ti-trash"></i></button>
      </div>
    </div>);

}

function SectionPlaceholder({ section }) {
  return (
    <div className="ctx-placeholder">
      <div style={{ fontFamily: "var(--ms-font-serif)", fontSize: 20, marginBottom: 6 }}>{section.title}</div>
      <div style={{ fontSize: 12, color: "var(--ms-fg-muted)" }}>AI-drafted from source. Same anatomy as the other sections — citations, editable text, mark confirmed.</div>
    </div>);

}

// ----- Citation chip (text-level, like variation I) -----
function CtxCite({ n, children }) {
  return (
    <span className="cite-target">
      {children}
      <sup className="cite-chip">{n}</sup>
    </span>);

}

// ----- Verification chip (named entity) -----
function CtxEntity({ name }) {
  const e = CTX_ENTITIES.find((x) => x.name === name);
  if (!e) return <span>{name}</span>;
  const isClient = e.kind === "client-product" || e.kind === "client-brand";
  return (
    <span className={"ctx-entity ctx-entity--" + (isClient ? "client" : "competitor")} title={(isClient ? "Gola " : "Competitor — " + e.brand + " · ") + e.kind}>
      {name}
      <i className={"ctx-entity__mark ti " + (isClient ? "ti-check" : "ti-external-link")}></i>
    </span>);

}

Object.assign(window, { ContextView });
