// ============================================================
// WORK PAGE — editorial magazine shelf with filters
// ============================================================

const WORK_ITEMS = [
  {
    id: 'globex',
    client: 'GLOBEX',
    sector: 'Enterprise SaaS',
    pillar: 'Customer Advocacy',
    service: 'Customer Advocacy',
    discipline: 'Reference programme',
    campaign: 'Always-on',
    title: 'A reference engine that turned 12 happy customers into a 38% net retention lift',
    excerpt: 'An always-on advocacy programme covering executive interviews, evidence assets, and analyst-grade reference workflow embedded with sales and CS.',
    challenge: 'Reference customers were ad-hoc, hard to find, and exhausted by repeat asks. Sales was losing deals to slower analyst-grade competitors.',
    solution: 'Built a tiered reference programme — bronze through platinum — with a public, searchable evidence library and clear rules of engagement.',
    creative: 'High-fidelity executive interviews captured on location with two-camera setups. Each interview produced six artefacts across three channels.',
    deliverables: 'Reference library · 18 executive videos · 24 written case studies · 6 analyst briefings · Internal enablement portal',
    result: '+38% net retention',
    resultDetail: 'Across the active reference base, year on year',
    accent: '#2CE6D6',
    bg: '#261244',
    feature: true,
  },
  {
    id: 'initech',
    client: 'INITECH',
    sector: 'Industrial Tech',
    pillar: 'Loyalty & Communities',
    service: 'Customer Advisory Board',
    discipline: 'Strategic community',
    campaign: 'Quarterly',
    title: 'A quarterly advisory board feeding an enterprise expansion motion',
    excerpt: 'Senior, NDA-protected board sessions for the top 30 strategic accounts — feeding product, marketing, and account expansion.',
    challenge: 'No structured channel for strategic input from top accounts. Expansion conversations were reactive.',
    solution: 'Established a private quarterly board with curated agenda and a dedicated insight-to-action pipeline.',
    creative: 'Each session captured as an editorial debrief, distributed to the wider customer base with attribution.',
    deliverables: '4 board sessions/year · Insight digests · Expansion playbook · Executive briefings',
    result: '2.4× expansion',
    resultDetail: 'Pipeline sourced from board accounts',
    accent: '#895EF7',
    bg: '#2E1754',
  },
  {
    id: 'hooli',
    client: 'HOOLI',
    sector: 'Marketing Cloud',
    pillar: 'Strategic Storytelling',
    service: 'Strategic Storytelling',
    discipline: 'Editorial campaign',
    campaign: 'Hero campaign',
    title: 'Documentary-grade customer films for a hero category campaign',
    excerpt: 'A six-film series that reframed a complex platform into human stories about the teams using it.',
    challenge: 'Product complexity was burying customer value. Sales decks were doing the talking.',
    solution: 'Built a journalistic story map across six customers, then produced documentary-style films and long-reads.',
    creative: 'Three-day on-site shoots. Verité interviews. Print-grade photography. No actors, no scripts.',
    deliverables: '6 short films · 6 long-form features · Microsite · Sales playbook · Event keynote',
    result: '+22% pipeline',
    resultDetail: 'Attributed to the campaign',
    accent: '#FF4D8A',
    bg: '#40465C',
  },
  {
    id: 'soylent',
    client: 'SOYLENT',
    sector: 'FinTech',
    pillar: 'Voice of the Customer',
    service: 'VOC Insight Activation',
    discipline: 'Continuous research',
    campaign: 'Always-on',
    title: 'Closing a 30-day sales gap with a self-service evidence library',
    excerpt: 'Operational VOC programme that surfaced the proof sales needed at the moment it was needed.',
    challenge: 'Sales asked CS for evidence in every late-stage deal. CS spent days hunting. Deals slipped.',
    solution: 'Built a tagged, role-based evidence library with automated content harvest from interviews and reviews.',
    creative: 'Evidence cards designed for fast scanning — quote, metric, sector, year. Designed to be linked from CRM.',
    deliverables: '190+ evidence cards · CRM integration · Quarterly refresh · Tagging taxonomy',
    result: '−30 days',
    resultDetail: 'Average late-stage cycle time',
    accent: '#4DA1F7',
    bg: '#252A3A',
  },
  {
    id: 'wonka',
    client: 'WONKA',
    sector: 'CPG / B2B',
    pillar: 'Loyalty & Communities',
    service: 'Loyalty & Communities',
    discipline: 'Customer community',
    campaign: 'Always-on',
    title: 'A senior customer community that produces quarterly evidence',
    excerpt: 'Closed-door, hosted community for category leaders — generating proof, peer connection, and partnership.',
    challenge: 'High-value customers had no peer network. Renewal conversations lacked relational depth.',
    solution: 'Designed a hosted membership programme with curated events, a private digest, and proof-asset co-creation.',
    creative: 'Editorial-grade member digest, salon-format events, member-byline thought leadership.',
    deliverables: 'Monthly digest · 8 events/year · Member directory · Co-authored reports',
    result: '12 quarterly assets',
    resultDetail: 'Co-produced with members each year',
    accent: '#21CBDD',
    bg: '#1C2A3F',
  },
  {
    id: 'massive',
    client: 'MASSIVE DYNAMIC',
    sector: 'Manufacturing',
    pillar: 'Customer Advocacy',
    service: 'Customer Advocacy',
    discipline: 'Lifecycle campaign',
    campaign: 'Lifecycle',
    title: 'Lifecycle proof for acquisition, retention, and expansion',
    excerpt: 'Three integrated proof programmes mapped to each stage of the customer lifecycle.',
    challenge: 'Marketing, sales, and CS were each producing proof — duplicating effort and missing the lifecycle.',
    solution: 'One operating model, three motions: acquire-stage proof, retain-stage proof, expand-stage proof.',
    creative: 'Sector-specific creative system. Modular video and written components. Hub-and-spoke distribution.',
    deliverables: 'Lifecycle playbook · 30 proof assets · Quarterly editorial calendar · Activation guides',
    result: '+18% NRR',
    resultDetail: 'Year on year, programme cohort',
    accent: '#FF7640',
    bg: '#3A1F12',
  },
];

function WorkHero() {
  return (
    <section className="hero">
      <div className="container">
        <div className="hero__inner">
          <span className="hero__kicker">Selected work</span>
          <h1 style={{ font: '700 clamp(44px, 6vw, 88px)/1 var(--font-family-base)', letterSpacing: '-0.045em' }}>
            Customer&#8209;powered<br/>growth, in practice.
          </h1>
          <p className="hero__lead">
            A curated selection of work where listening, advocacy, story, and community
            compounded into measurable commercial outcomes.
          </p>
        </div>
      </div>
    </section>
  );
}

function WorkIndex({ onOpenCase }) {
  const [filters, setFilters] = React.useState({
    sector: 'All',
    service: 'All',
    discipline: 'All',
    campaign: 'All',
    pillar: 'All',
  });

  const filterOptions = {
    sector: ['All', 'Enterprise SaaS', 'Industrial Tech', 'Marketing Cloud', 'FinTech', 'CPG / B2B', 'Manufacturing'],
    service: ['All', 'VOC Insight Activation', 'Customer Advocacy', 'Strategic Storytelling', 'Loyalty & Communities', 'Customer Advisory Board'],
    discipline: ['All', 'Reference programme', 'Strategic community', 'Editorial campaign', 'Continuous research', 'Customer community', 'Lifecycle campaign'],
    campaign: ['All', 'Always-on', 'Quarterly', 'Hero campaign', 'Lifecycle'],
    pillar: ['All', 'Voice of the Customer', 'Customer Advocacy', 'Strategic Storytelling', 'Loyalty & Communities'],
  };

  const filterLabel = {
    sector: 'Industry / Sector',
    service: 'Service',
    discipline: 'Discipline',
    campaign: 'Campaign type',
    pillar: 'Growth pillar',
  };

  const setFilter = (key, value) => setFilters(f => ({ ...f, [key]: value }));

  const matches = (item) => {
    if (filters.sector !== 'All' && item.sector !== filters.sector) return false;
    if (filters.service !== 'All' && item.service !== filters.service) return false;
    if (filters.discipline !== 'All' && item.discipline !== filters.discipline) return false;
    if (filters.campaign !== 'All' && item.campaign !== filters.campaign) return false;
    if (filters.pillar !== 'All' && item.pillar !== filters.pillar) return false;
    return true;
  };

  const visible = WORK_ITEMS.filter(matches);
  const [feature, ...rest] = visible;

  // Pack remaining into editorial rows: 2-1, 1-1-1, 2-1
  const rows = [];
  let cursor = 0;
  const patterns = ['row-1-1-1', 'row-2-1', 'row-1-2', 'row-1-1-1'];
  let pIndex = 0;
  while (cursor < rest.length) {
    const pattern = patterns[pIndex % patterns.length];
    const take = pattern === 'row-1-1-1' ? 3 : 2;
    rows.push({ pattern, items: rest.slice(cursor, cursor + take) });
    cursor += take;
    pIndex += 1;
  }

  return (
    <>
      <section className="section section--canvas" style={{ paddingTop: 0 }}>
        <div className="container">
          {/* Filter bar */}
          <div style={{
            background: '#fff',
            border: '1px solid var(--border-subtle)',
            borderRadius: 'var(--radius-lg)',
            padding: 24,
            display: 'flex', flexDirection: 'column', gap: 20,
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Icon name="filter" size={18} color="var(--text-deep-grape)" />
                <span style={{ font: 'var(--type-label-md)', color: 'var(--text-deep-grape)' }}>Filter the shelf</span>
              </div>
              <div style={{ font: 'var(--type-caption)', color: 'var(--text-muted)', letterSpacing: 'var(--tracking-caption)' }}>
                {visible.length} of {WORK_ITEMS.length} case studies
              </div>
            </div>
            {Object.keys(filterOptions).map(key => (
              <div key={key} className="work-filter__group" style={{ paddingTop: 0 }}>
                <span className="work-filter__label" style={{ minWidth: 130 }}>{filterLabel[key]}</span>
                {filterOptions[key].map(opt => (
                  <button key={opt}
                    className={"filter-chip" + (filters[key] === opt ? ' is-selected' : '')}
                    onClick={() => setFilter(key, opt)}>
                    {opt}
                  </button>
                ))}
              </div>
            ))}
          </div>

          {visible.length === 0 && (
            <div style={{
              textAlign: 'center', padding: '80px 0',
              color: 'var(--text-muted)', font: 'var(--type-body-md)',
            }}>
              No case studies match these filters yet. Try clearing one.
            </div>
          )}

          {feature && (
            <div className="shelf">
              <FeatureCase item={feature} onOpen={() => onOpenCase(feature.id)} />
              {rows.map((row, i) => (
                <div key={i} className={"shelf__row " + row.pattern}>
                  {row.items.map((it, j) => (
                    <StandardCase
                      key={it.id}
                      item={it}
                      onOpen={() => onOpenCase(it.id)}
                      tall={row.pattern.startsWith('row-2-1') && j === 0 || row.pattern.startsWith('row-1-2') && j === 1}
                    />
                  ))}
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    </>
  );
}

function FeatureCase({ item, onOpen }) {
  return (
    <article className="workcard workcard--feature" onClick={onOpen}>
      <div className="workcard__cover" style={{ background: item.bg }}>
        <div className="workcard__topbar">
          <span className="workcard__pill">{item.pillar}</span>
          <span className="workcard__pill" style={{ background: 'rgba(0,0,0,0.18)' }}>{item.sector}</span>
        </div>
        <div className="workcard__metric" style={{ '--accent': item.accent }}>
          {item.result}
          <span className="small">{item.resultDetail}</span>
        </div>
      </div>
      <div className="workcard__body">
        <div className="workcard__meta">
          <span>{item.client}</span><span className="sep">/</span>
          <span>{item.service}</span>
        </div>
        <h3 className="workcard__title">{item.title}</h3>
        <p className="workcard__excerpt">{item.excerpt}</p>
        <div className="workcard__detail">
          <div>
            <span className="k">Challenge</span>
            <span className="v">{item.challenge}</span>
          </div>
          <div>
            <span className="k">Solution</span>
            <span className="v">{item.solution}</span>
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <span className="k">Deliverables</span>
            <span className="v">{item.deliverables}</span>
          </div>
        </div>
        <div className="workcard__cta">
          Read the case study <Icon name="arrowRight" size={14} color="var(--text-deep-grape)" />
        </div>
      </div>
    </article>
  );
}

function StandardCase({ item, onOpen, tall }) {
  return (
    <article className={"workcard" + (tall ? " workcard--tall" : "")} onClick={onOpen}>
      <div className="workcard__cover" style={{ background: item.bg }}>
        <div className="workcard__topbar">
          <span className="workcard__pill">{item.pillar}</span>
          <span className="workcard__pill" style={{ background: 'rgba(0,0,0,0.18)' }}>{item.sector}</span>
        </div>
        <div className="workcard__metric" style={{ '--accent': item.accent, fontSize: 'clamp(36px, 4.4vw, 60px)' }}>
          {item.result}
          <span className="small">{item.resultDetail}</span>
        </div>
      </div>
      <div className="workcard__body">
        <div className="workcard__meta">
          <span>{item.client}</span><span className="sep">/</span>
          <span>{item.service}</span>
        </div>
        <h3 className="workcard__title">{item.title}</h3>
        <p className="workcard__excerpt">{item.excerpt}</p>
        <div className="workcard__cta" style={{ marginTop: 8 }}>
          Read the case study <Icon name="arrowRight" size={14} color="var(--text-deep-grape)" />
        </div>
      </div>
    </article>
  );
}

window.WorkHero = WorkHero;
window.WorkIndex = WorkIndex;
window.WORK_ITEMS = WORK_ITEMS;
