﻿// Full thesis — Ethical AI and Indigenous Storytelling (Nadine Young, 2026)

const CHAPTERS = [
  { n:'ab', title:'Abstract', sub:'Summary of research and findings', free: true },
  { n:'ac', title:'Acknowledgements', sub:'With gratitude', free: true },
  { n:'01', title:'Introduction', sub:'When AI Gets Māori Wrong' },
  { n:'02', title:'Literature Review', sub:'AI, Language & Indigenous Data Sovereignty' },
  { n:'03', title:'Methodology', sub:'Kaupapa Māori Research Paradigm' },
  { n:'04', title:'Findings', sub:'Five Interconnected Themes' },
  { n:'05', title:'Discussion', sub:'What This Means in Practice' },
  { n:'06', title:'Critical Reflection', sub:'Finding My Voice and My Value' },
  { n:'07', title:'Conclusion & Recommendations', sub:'Guidance for Organisations, Government & Iwi' },
  { n:'st', title:'AI & Storytelling', sub:'Interview deep dive — additional questions' },
  { n:'gl', title:'Glossary', sub:'Te Reo Māori terms used throughout' },
  { n:'rf', title:'References', sub:'Bibliography and citations' },
  { n:'mb', title:'Miro Board', sub:'Thematic analysis visualisation' },
];

function ThesisPage() {
  const [unlocked, setUnlocked] = React.useState(
    () => localStorage.getItem('thesis_access') === '1'
  );
  const [activeChapter, setActiveChapter] = React.useState('ab');
  const contentRef = React.useRef(null);

  // Email activation states
  const [emailSent, setEmailSent]       = React.useState(false);   // show "check your email" screen
  const [sentToEmail, setSentToEmail]   = React.useState('');       // the address we sent to
  const [activating, setActivating]     = React.useState(false);   // verifying token from URL
  const [activateErr, setActivateErr]   = React.useState('');      // error during activation

  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);

    // After Stripe payment: session_id returned in URL → call thesis-activate
    // which verifies payment and sends the activation email
    const sessionId = params.get('thesis_session');
    if (sessionId) {
      window.history.replaceState({}, '', '/#/thesis'); // clean URL immediately
      fetch('/api/thesis-activate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ session_id: sessionId }),
      })
        .then(r => r.json())
        .then(data => {
          if (data.sent) {
            setSentToEmail(data.email);
            setEmailSent(true);
          } else {
            setActivateErr('Something went wrong sending your access email. Please contact Nadine directly.');
          }
        })
        .catch(() => setActivateErr('Could not send your access email. Please contact Nadine directly.'));
      return;
    }

    // Activation link from email: thesis_token in URL → call thesis-verify
    const token = params.get('thesis_token');
    if (token) {
      setActivating(true);
      window.history.replaceState({}, '', '/#/thesis'); // clean URL
      fetch('/api/thesis-verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token }),
      })
        .then(r => r.json())
        .then(data => {
          setActivating(false);
          if (data.valid) {
            localStorage.setItem('thesis_access', '1');
            localStorage.setItem('thesis_token', token); // stored for API chapter requests
            setUnlocked(true);
          } else {
            setActivateErr('This access link is invalid or has expired. Please contact Nadine.');
          }
        })
        .catch(() => {
          setActivating(false);
          setActivateErr('Could not verify your access link. Please try again or contact Nadine.');
        });
    }
  }, []);

  return (
    <div className="route-enter">

      {/* Hero */}
      <section style={{
        background:'var(--ink)', color:'var(--bg)',
        padding:'7rem 40px 5rem', position:'relative', overflow:'hidden',
        textAlign:'center',
      }}>
        <div style={{
          position:'absolute', inset:0, pointerEvents:'none',
          backgroundImage:'linear-gradient(rgba(239,230,218,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(239,230,218,0.03) 1px, transparent 1px)',
          backgroundSize:'80px 80px',
        }}/>
        <img src="assets/logo.png" alt="" aria-hidden="true" style={{
          position:'absolute', bottom:'-4%', right:'-4%', width:'40%',
          opacity:0.04, filter:'brightness(0) invert(1)', pointerEvents:'none',
        }}/>
        <div style={{position:'relative', zIndex:2, maxWidth:820, margin:'0 auto'}}>
          <div className="label" style={{justifyContent:'center', color:'rgba(239,230,218,0.5)', marginBottom:'1.5rem'}}>
            AcademyEX · Master of Technological Futures · April 2026
          </div>
          <h1 className="display" style={{
            fontSize:'clamp(2.2rem, 5vw, 5rem)', color:'var(--bg)',
            lineHeight:1.0, letterSpacing:'-0.02em', marginBottom:'1.5rem',
          }}>
            Ethical AI and<br/>
            <em style={{color:'var(--accent)'}}>Indigenous Storytelling</em>
          </h1>
          <p style={{
            fontSize:'clamp(1rem, 1.5vw, 1.15rem)', color:'rgba(239,230,218,0.6)',
            lineHeight:1.8, maxWidth:560, margin:'0 auto 2.5rem',
          }}>
            Protecting Language, Data, and Culture
          </p>
          <div className="label" style={{justifyContent:'center', color:'rgba(239,230,218,0.4)', marginBottom:'2.5rem'}}>
            Nadine Young · Supervisor: Jade Tang-Taylor
          </div>
          <div style={{display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap'}}>
            <a href="#abstract" className="btn btn-accent">Read Abstract <span className="arrow">→</span></a>
            {!unlocked && (
              <button onClick={() => document.getElementById('paywall')?.scrollIntoView({behavior:'smooth'})} className="btn" style={{
                border:'1px solid rgba(239,230,218,0.25)', color:'var(--bg)', background:'none',
              }}>Unlock Full Thesis — NZ$35 <span className="arrow">→</span></button>
            )}
            {unlocked && (
              <button className="btn" style={{
                border:'1px solid rgba(239,230,218,0.25)', color:'var(--accent)', background:'none', cursor:'default',
              }}>Full access granted</button>
            )}
          </div>
          <div style={{
            display:'flex', justifyContent:'center', marginTop:'4rem',
            borderTop:'1px solid rgba(239,230,218,0.1)', paddingTop:'2.5rem',
          }}>
            {[['7','Chapters'],['10','Expert interviews'],['20','Survey responses'],['5','Key themes']].map(([n, label], i) => (
              <div key={n} style={{
                padding:'0 2.5rem', textAlign:'center',
                borderRight: i < 3 ? '1px solid rgba(239,230,218,0.1)' : 'none',
              }}>
                <span className="display" style={{fontSize:'2.8rem', color:'rgba(239,230,218,0.9)', display:'block', fontStyle:'italic'}}>{n}</span>
                <p className="mono" style={{fontSize:10, letterSpacing:'0.14em', textTransform:'uppercase', color:'rgba(239,230,218,0.35)', marginTop:6, maxWidth:'none'}}>{label}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Main layout */}
      <div className="thesis-layout">

        {/* Sidebar */}
        <aside className="thesis-sidebar" style={{paddingTop:64}}>
          <div style={{position:'sticky', top:96}}>
            <div className="label" style={{marginBottom:20}}>Chapters</div>
            <nav style={{display:'flex', flexDirection:'column', gap:4}}>
              {CHAPTERS.map(c => (
                <button key={c.n} onClick={() => { setActiveChapter(c.n); if (contentRef.current) { contentRef.current.scrollIntoView({behavior:'smooth', block:'start'}); } }} style={{
                  textAlign:'left', padding:'10px 14px', borderRadius:8,
                  background: activeChapter === c.n ? 'var(--bg-2)' : 'transparent',
                  border: activeChapter === c.n ? '1px solid var(--hair)' : '1px solid transparent',
                  cursor:'pointer', transition:'all .2s',
                  display:'flex', alignItems:'center', gap:12,
                }}>
                  <span className="mono" style={{fontSize:10, color:'var(--accent)', minWidth:20}}>{c.n}</span>
                  <div>
                    <div style={{fontSize:13, fontWeight:500, color:'var(--ink)'}}>{c.title}</div>
                    <div className="mono" style={{fontSize:10, color:'var(--muted)', marginTop:2}}>{c.sub}</div>
                  </div>
                  {!c.free && !unlocked && (
                    <span style={{marginLeft:'auto', fontSize:11, color:'var(--hair)'}}>lock</span>
                  )}
                </button>
              ))}
            </nav>

            <div className="hair" style={{margin:'24px 0'}}/>
            <div className="label" style={{marginBottom:12}}>Research details</div>
            {[
              ['Institution', 'AcademyEX'],
              ['Programme', 'Master of Technological Futures'],
              ['Supervisor', 'Jade Tang-Taylor'],
              ['Ethics approval', 'MTF.8888.279'],
              ['Submitted', 'April 2026'],
            ].map(([k, v]) => (
              <div key={k} style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, padding:'8px 0', borderBottom:'1px solid var(--hair)', fontSize:12}}>
                <span className="mono" style={{color:'var(--muted)', fontSize:10}}>{k.toUpperCase()}</span>
                <span style={{color:'var(--ink)'}}>{v}</span>
              </div>
            ))}
          </div>
        </aside>

        {/* Content */}
        <main ref={contentRef} style={{paddingTop:64, paddingBottom:96}}>
          {/* Mobile chapter selector */}
          <select
            className="thesis-chapter-select"
            value={activeChapter}
            onChange={e => setActiveChapter(e.target.value)}
          >
            {CHAPTERS.map(c => (
              <option key={c.n} value={c.n} disabled={!c.free && !unlocked}>
                {c.n.match(/^\d+$/) ? `Chapter ${c.n}` : c.title}{!c.free && !unlocked ? ' 🔒' : ''}
              </option>
            ))}
          </select>

          {activeChapter === 'ab' ? (
            <>
              {/* Abstract */}
              <div id="abstract" style={{marginBottom:64}}>
                <div className="label" style={{marginBottom:16}}>Abstract</div>
                <p style={{fontSize:'var(--step-lg)', fontFamily:'var(--f-display)', fontStyle:'italic', lineHeight:1.5, marginBottom:24, maxWidth:'none'}}>
                  Artificial intelligence (AI) is rapidly transforming how language, knowledge, and culture are created and shared. For Indigenous communities, including Māori in Aotearoa, this presents both significant opportunities and serious risks.
                </p>
                <p style={{color:'var(--ink-2)', lineHeight:1.8, marginBottom:16, maxWidth:'none'}}>
                  While AI has the potential to support the revitalisation of te reo Māori, it also introduces challenges such as misrepresentation, data extraction, and the erosion of cultural integrity. Despite growing awareness of these issues, there remains limited research that translates Indigenous data sovereignty principles into practical guidance for AI use.
                </p>
                <p style={{color:'var(--ink-2)', lineHeight:1.8, marginBottom:16, maxWidth:'none'}}>
                  This study addresses that gap through a kaupapa Māori research approach, guided by the Te Ara Tika ethical framework. The research draws on ten semi-structured interviews with Māori and Indigenous experts working across AI, data sovereignty, and cultural leadership, as well as twenty survey responses capturing broader community perspectives. Informal conversations with Pacific community members during the research period further affirmed that the concerns identified are not unique to Māori — Pacific communities face parallel challenges around community control, cultural integrity, and the risk of AI being built without adequate internal community engagement. Thematic analysis identified five interconnected themes: AI as a crossroads of risk and opportunity; data sovereignty as a non-negotiable foundation; the need for tikanga-based governance; the importance of community authority and co-design; and a persistent gap between principle and practice.
                </p>
                <p style={{color:'var(--ink-2)', lineHeight:1.8, marginBottom:16, maxWidth:'none'}}>
                  The findings extend existing literature by demonstrating how these issues are experienced in real-world contexts and by introducing practical frameworks, including the classification of Māori data as noa, tapu, or rāhui. The research argues that the primary challenge is not a lack of awareness, but a lack of structures to support implementation.
                </p>
                <p style={{color:'var(--ink-2)', lineHeight:1.8, marginBottom:32, maxWidth:'none'}}>
                  Ultimately, this study concludes that the future of AI in relation to te reo Māori will be shaped by governance rather than technology alone. Ensuring culturally aligned outcomes requires Māori-led authority, practical frameworks, and collective responsibility embedded within systems and decision-making processes.
                </p>
              </div>

              <div className="hair" style={{marginBottom:64}}/>

              {/* Five themes overview */}
              <div style={{marginBottom:64}}>
                <div className="label" style={{marginBottom:8}}>Key findings · Ngā kitenga</div>
                <h2 style={{marginTop:12, marginBottom:40, maxWidth:'20ch'}}>Five interconnected themes.</h2>
                <div style={{display:'flex', flexDirection:'column', borderTop:'1px solid var(--hair)'}}>
                  {[
                    { n:'01', title:'AI as a Crossroads of Risk and Opportunity', body:'AI tools offer real potential for language revitalisation and accessibility — yet introduce misrepresentation, data extraction, and cultural harm when built without Indigenous oversight.' },
                    { n:'02', title:'Data Sovereignty as a Non-Negotiable Foundation', body:'Indigenous data sovereignty is not an ethical preference — it is a legal and cultural obligation. Māori data must be classified as noa, tapu, or rāhui before any AI system touches it.' },
                    { n:'03', title:'Governance Must Be Tikanga-Based, Not Tokenistic', body:'Surface-level cultural consultation is insufficient. Governance frameworks must be grounded in tikanga and must carry real authority over decisions, not merely provide advice.' },
                    { n:'04', title:'Community Authority and Co-Design as the Only Viable Path', body:'AI systems that affect Indigenous communities must be co-designed with those communities. Engagement after the fact is not co-design — it is consultation, and it is not enough.' },
                    { n:'05', title:'The Gap Between Principle and Practice', body:'The primary challenge is not a lack of awareness of these issues — it is the absence of structures that support implementation. Principles without process produce no change.' },
                  ].map((t) => (
                    <div key={t.n} style={{
                      display:'grid', gridTemplateColumns:'64px 1fr',
                      gap:32, padding:'28px 0', borderBottom:'1px solid var(--hair)', alignItems:'start',
                    }}>
                      <span className="display" style={{fontSize:48, fontStyle:'italic', color:'var(--accent)', lineHeight:1}}>{t.n}</span>
                      <div>
                        <h4 style={{fontSize:'var(--step-xl)', marginBottom:10}}>{t.title}</h4>
                        <p style={{fontSize:15, color:'var(--ink-2)', lineHeight:1.7, maxWidth:'none'}}>{t.body}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </>
          ) : activeChapter === 'ac' ? (
            <Acknowledgements />
          ) : (
            <>
              {!unlocked ? (
                /* ── Activation in progress (token from email link) ── */
                activating ? (
                  <div style={{padding:'80px 0', textAlign:'center'}}>
                    <p style={{color:'var(--muted)', fontSize:15}}>Verifying your access…</p>
                  </div>
                ) : activateErr ? (
                  /* ── Activation error ── */
                  <div style={{padding:'60px 0', textAlign:'center', maxWidth:520, margin:'0 auto'}}>
                    <p style={{color:'var(--rust)', fontSize:15, marginBottom:16}}>{activateErr}</p>
                    <a href="mailto:hello@nrxauaha.com" className="btn btn-outline" style={{display:'inline-flex'}}>Email Nadine →</a>
                  </div>
                ) : emailSent ? (
                  /* ── Email sent — ask user to check inbox ── */
                  <div style={{padding:'60px 0', maxWidth:560, margin:'0 auto', textAlign:'center'}}>
                    <div style={{
                      background:'var(--ink)', borderRadius:16, padding:'48px 40px',
                      position:'relative', overflow:'hidden',
                    }}>
                      <div style={{position:'relative', zIndex:2}}>
                        <div className="label" style={{justifyContent:'center', color:'rgba(239,230,218,0.5)', marginBottom:20}}>Access email sent</div>
                        <h2 className="display" style={{color:'var(--bg)', fontSize:'2rem', fontStyle:'italic', marginBottom:16}}>Check your inbox.</h2>
                        <p style={{color:'rgba(239,230,218,0.65)', fontSize:15, lineHeight:1.7, marginBottom:8}}>
                          We've sent your activation link to:
                        </p>
                        <p style={{color:'var(--accent)', fontSize:15, fontWeight:600, marginBottom:24, wordBreak:'break-all'}}>{sentToEmail}</p>
                        <p style={{color:'rgba(239,230,218,0.5)', fontSize:13, lineHeight:1.6}}>
                          Click the link in that email to unlock the full thesis. Check your spam folder if you don't see it within a few minutes.
                        </p>
                      </div>
                    </div>
                  </div>
                ) : (
                  /* ── Normal paywall ── */
                  activeChapter === '01' ? (
                    <>
                      <Chapter01 />
                      <div id="paywall"><PaywallGate setEmailSent={setEmailSent} setSentToEmail={setSentToEmail} /></div>
                    </>
                  ) : (
                    <div id="paywall"><PaywallGate setEmailSent={setEmailSent} setSentToEmail={setSentToEmail} /></div>
                  )
                )
              ) : (
                <UnlockedContent activeChapter={activeChapter} />
              )}
            </>
          )}

        </main>
      </div>
    </div>
  );
}

// ─── Shared primitives ────────────────────────────────────────────────────────

const P = ({children, style}) => (
  <p style={{color:'var(--ink-2)', lineHeight:1.8, marginBottom:16, maxWidth:'none', ...style}}>{children}</p>
);

const SectionHeading = ({children}) => (
  <h4 style={{fontSize:'var(--step-xl)', marginBottom:12, marginTop:40, color:'var(--ink)'}}>{children}</h4>
);

const Quote = ({children, attr}) => (
  <div style={{
    borderLeft:'3px solid var(--accent)', paddingLeft:24, margin:'28px 0',
    background:'var(--bg-2)', padding:'20px 24px', borderRadius:'0 8px 8px 0',
  }}>
    <p style={{
      fontFamily:'var(--f-display)', fontStyle:'italic', fontSize:17,
      lineHeight:1.65, color:'var(--ink)', marginBottom:attr ? 10 : 0, maxWidth:'none',
    }}>{children}</p>
    {attr && <p className="mono" style={{fontSize:11, color:'var(--muted)', letterSpacing:'0.08em', marginBottom:0}}>{attr}</p>}
  </div>
);

const Figure = ({src, alt, caption}) => (
  <div style={{margin:'40px 0'}}>
    <img src={src} alt={alt} style={{
      width:'100%', borderRadius:8, border:'1px solid var(--hair)', display:'block',
    }}/>
    {caption && (
      <p className="mono" style={{fontSize:11, color:'var(--muted)', marginTop:10, letterSpacing:'0.04em'}}>{caption}</p>
    )}
  </div>
);

// ─── Chapter 1 (free) ─────────────────────────────────────────────────────────

function Chapter01() {
  return (
    <div style={{marginBottom:64}}>
      <div className="label" style={{marginBottom:8}}>Chapter One</div>
      <h2 style={{marginTop:12, marginBottom:40}}>Introduction</h2>

      <SectionHeading>1.1 Introduction</SectionHeading>
      <P>For most of my life, I knew I was Māori but didn't publicly acknowledge it. I felt I wasn't the right skin colour, couldn't speak te reo, and had been told by trusted people not to trust Māori. As a result, I kept my whakapapa quietly, feeling unsure of my belonging or whether I had the right to claim a place. What I felt wasn't pride or connection but a sense of stillness — a reluctance to fully engage. This is what colonisation does: it not only separates language from land but also sows doubt about one's own identity, community, and worth (Penetito & Waitere, 2010).</P>
      <P>This experience isn't unique but reflects a broader, intergenerational impact of language loss, where disconnection isn't just historical but ongoing. The feeling of whakamā — hesitation and shame in reconnecting with te reo Māori — is well documented among Māori who were denied access to their language (AUT, 2024). For many, returning to reo involves navigating absence, uncertainty, and questions of belonging deeply embedded by colonisation over time.</P>
      <P>In this context, AI can seem both an opportunity and a risk. For those reconnecting with language, AI tools can seem like a lifeline — providing translation, pronunciation, and access that were previously unavailable. But this reliance requires trust, assuming these systems can accurately capture language and meaning. Increasing evidence suggests this assumption is flawed.</P>
      <P>For someone reconnecting, a mistranslation isn't just misleading; it can fill the gaps left by colonisation with superficially correct knowledge that lacks underlying whakapapa. AI might not only reproduce errors but also reshape the understanding of language and identity. This is significant because we are experiencing a major shift in how language is encountered, transmitted, and normalised. Generative AI, machine translation, and speech tech are no longer emerging; they are now integral to education, healthcare, government, and daily life (Royal Society Te Apārangi, 2024).</P>
      <P>For widely spoken languages, this shift increases scale and accessibility. But for te reo Māori, which is still recovering and where only about 21 per cent of Māori report conversational proficiency, the implications are more complex. The same technologies that support Māori also pose risks that are not yet fully understood or regulated (Te Taura Whiri i te Reo Māori, 2025).</P>

      <SectionHeading>1.2 When AI Gets Māori Wrong</SectionHeading>
      <P>The dangers of AI misrepresenting te reo Māori are real and ongoing. They are evidenced by documented cases where key terms are mistranslated and linguistic structures are misinterpreted. For example, the gender-neutral pronoun <em>ia</em> is often assigned a gender based on stereotypes—female for domestic roles and male for leadership—though it has no gender in te reo Māori (Taiuru, 2021). Additionally, cultural practices such as the haka are often reduced to mere performance, losing their relational, historical, and spiritual significance (Mead, 2019).</P>
      <P>These issues are not isolated errors but stem from systems trained primarily on English data, in which Māori concepts are either missing or underrepresented (Navigli et al., 2023). Consequently, large language models tend to confidently reproduce inaccuracies at scale. Testing of generative Māori language tools in 2024 revealed that although these systems are improving, fixing errors often takes longer than manual translation. Even more concerning is the potential for AI-generated Māori to become an authoritative resource for learners worldwide, risking the entrenchment of errors in long-term language use (AI Researchers NZ, 2024).</P>
      <P>This underscores a core problem: AI systems don't just mirror knowledge — they influence its formation. When mistakes spread through popular platforms, they build up and become normalised. Eventually, this can lead to a version of te reo Māori that is considered correct online, even though it may be detached from tikanga, context, and whakapapa.</P>
      <P>The issue goes beyond just technical accuracy to include the underlying assumptions behind AI usage. Recently, I was asked to translate a Māori phrase for an AI agent. Since I am still relearning my reo and not yet fluent, I recommend consulting a qualified language expert. However, they dismissed this, claiming it was "only one word" and that their client needed data for the AI because the client couldn't pronounce the word and didn't want to learn. I questioned how tikanga was incorporated into this approach, feeling it was more about checking a box for the organisation than about truly understanding the word's meaning and pronunciation.</P>
      <P>That moment exposed something deeper: the tendency to reduce language, culture, and meaning to something easily extracted and treated as transactional. For those relearning reo, each kupu is more than just a word; it carries significance within whakapapa and tikanga that govern how knowledge is shared. Māori data, including language, is recognised as taonga with cultural, relational, and intergenerational importance (JIPEL, 2023). To dismiss it as "just data" reflects an ongoing pattern of extraction in which speed and convenience take precedence over relationships, authority, and proper process (Taiuru, 2024a).</P>
      <P>When these assumptions are integrated into AI systems, they cease to be isolated decisions. Instead, they become embedded in the infrastructure that shapes how language and culture are understood at large.</P>

      <SectionHeading>1.3 Continuity, Not Coincidence</SectionHeading>
      <P>These dynamics are interconnected. Colonial education policies that enforced English-only instruction deliberately suppressed te reo Māori, disrupting its transmission across generations (Penetito & Waitere, 2010). This interference went beyond language, breaking the channels through which whakapapa, identity, and cultural belonging were preserved and passed down.</P>
      <P>As a result, many Māori are now reconnecting with a language that colonisation had made difficult to access (Penetito & Waitere, 2010). This is not just a distant historical event; it is a reality experienced daily. Like many Māori, I was raised with an awareness of my culture, but I did not have full access to it.</P>
      <P>What is becoming clearer is the ongoing link between this historical upheaval and current digital developments. AI systems that gather Māori data without permission, distort cultural ideas, and favour Western knowledge frameworks are not neutral tools (Taiuru, as cited in RNZ, 2023). Instead, they function within a context already influenced by extraction and dispossession.</P>
      <P>As demonstrated by the Pacific Data Sovereignty Network (2025), commercial AI frequently mirrors colonial patterns by taking Indigenous knowledge without proper authority, relationship, or reciprocity. In this context, AI doesn't create entirely new risks but rather magnifies existing ones. When Māori language and culture are shaped externally—without tikanga or Māori authority—it signifies a continuation of historical processes in a digital format.</P>
      <P>Recognising this continuity is fundamental to this research. It frames AI not merely as an isolated technological challenge but as an integral component of a larger system of power, governance, and knowledge creation that requires critical analysis.</P>

      <SectionHeading>1.4 The Gap This Research Addresses</SectionHeading>
      <P>Despite increased awareness of these issues, notable gaps remain in how AI interacts with Indigenous languages in practice. Māori data and language are increasingly integrated into global AI systems, often without proper consent, oversight, or governance (Taiuru, 2024b). Although frameworks such as Te Tiriti o Waitangi, the Māori Language Act, Te Mana Raraunga, and Indigenous data sovereignty principles exist, they are not consistently applied in AI development settings that emphasise speed, scale, and commercial interests (Te Kāhui Raraunga, 2024; Lilley et al., 2024).</P>
      <P>Empirical evidence underscores the significant gap. A 2025 audit revealed that several government agencies lacked a basic definition of Māori data, and that no local councils had adopted comprehensive Māori data governance frameworks (Taiuru, 2025c). This shows that the disconnect between principles and actual practice is not just theoretical — it is embedded systemically.</P>
      <P>Existing research has highlighted major risks like mistranslation, cultural commodification, and a lack of Indigenous-led oversight. Still, there is limited scholarship that directly incorporates the voices of Māori and Indigenous experts to define what responsible, tikanga-aligned AI practices should entail in real-world settings (Maimoa Creative, 2024). Even fewer studies have translated these insights into practical guidance for organisations working with AI in Aotearoa, New Zealand.</P>
      <P>This gap is further widened by structural challenges in the technology sector. Māori representation in AI-related fields is very low, with estimates indicating participation of less than 1% (Matihiko, 2025). This restricts Māori-led governance and increases dependence on systems created without Indigenous perspectives.</P>
      <P>The need to address this gap is growing more urgent. Large language models are expanding quickly, often without Indigenous oversight (Navigli et al., 2023). When inaccuracies become embedded in widely used systems, correcting them becomes challenging, especially given the rapid pace of technological adoption. The window for establishing culturally grounded governance before these patterns become entrenched is narrowing (Royal Society Te Apārangi, 2024).</P>

      <SectionHeading>1.5 Purpose and Approach</SectionHeading>
      <P>This research does not aim to develop AI tools or train language models. Instead, its goal is to establish a culturally rooted ethical framework to foster responsible AI engagement related to te reo Māori and Māori storytelling.</P>
      <P>By conducting semi-structured interviews with Māori and Indigenous specialists—including technologists, cultural leaders, and practitioners—the study explores current interactions between AI and Indigenous language and knowledge. It also identifies governance principles needed to ensure that this engagement remains safe, culturally appropriate, and sovereignty-affirming.</P>
      <P>A Māori-first approach is not merely a methodological choice; it is essential due to the cultural, linguistic, and ethical stakes involved. Only Māori can define the proper use, representation, and safeguarding of their language and cultural knowledge. This research aims to amplify that authority, rather than diminish it.</P>
      <P>The goal is to create guidance that is both academically sound and practically useful for organisations, policymakers, and practitioners in Aotearoa working with AI in te reo Māori contexts. Additionally, the study contributes to broader international discussions on Indigenous data sovereignty and AI governance (Hudson et al., 2010).</P>
      <P>The following questions reflect both the scope of this inquiry and the urgency behind it — each grounded in the realities described above and pointing toward the practical guidance this research aims to produce.</P>
      <P style={{fontWeight:500, color:'var(--ink)'}}>Primary Research Question:</P>
      <P>How can AI technologies be governed and applied in ways that protect and enhance Māori language, storytelling, and cultural integrity in Aotearoa, while upholding Indigenous data sovereignty, tikanga-based governance, and whānau, hapū, and iwi control?</P>
      <P style={{fontWeight:500, color:'var(--ink)'}}>Sub-Questions:</P>
      <ul style={{color:'var(--ink-2)', lineHeight:1.8, paddingLeft:24, marginBottom:16}}>
        <li>What are the ethical risks and opportunities of using AI for Māori language and storytelling, and how do these compare with other Indigenous contexts?</li>
        <li>How do Māori-led and Indigenous-led AI initiatives differ from commercial approaches in governance, data use, and cultural safety?</li>
        <li>What governance principles and ethical frameworks are required to ensure culturally aligned AI use for Māori?</li>
        <li>How do Māori define cultural integrity, accuracy, and trust when AI is used for language and storytelling?</li>
        <li>What practical guidance can support organisations using AI for te reo Māori in ways that uphold tikanga and sovereignty?</li>
      </ul>

      <SectionHeading>1.6 The Opportunity Ahead</SectionHeading>
      <P>While the risks are considerable, this research is rooted in AI's potential. When properly managed, AI can meaningfully support te reo Māori by improving accessibility, aiding language learning, and fostering connections within communities around cultural knowledge (Taiuru, as cited in RNZ, 2023).</P>
      <P>For Māori striving to reclaim and revitalise their language after generations of disruption, this potential is especially important. However, it requires a fundamental change in how AI systems are designed, governed, and implemented. Māori must lead this process—not just as consultants on the periphery, but as the main authorities shaping how their language and culture interact with these technologies from the ground up.</P>
      <P>This thesis aims to explore what such leadership looks like in practice and what changes are needed to enable it.</P>
    </div>
  );
}

// ─── Paywall Gate ─────────────────────────────────────────────────────────────

function Acknowledgements() {
  return (
    <div id="acknowledgements" style={{marginBottom:64}}>
      <div className="label" style={{marginBottom:16}}>Acknowledgements</div>
      <h2 style={{marginBottom:40, maxWidth:'28ch'}}>He aha te mea nui o te ao?<br/><em style={{color:'var(--accent)', fontStyle:'italic'}}>He tangata.</em></h2>

      {[
        `This thesis represents a journey that has been just as personal as it has been academic, and it would not have been possible without the support of many people. What began as a research project became something much deeper — a process of growth, reflection, and reconnection with who I am and the path I am choosing to walk.`,
        `There were moments of self-doubt and challenge — especially in balancing life, work, and study — but also moments of clarity and pride that reminded me why this work matters, not just academically, but personally and for the communities it speaks to.`,
        `This research has not been done in isolation. It has been shaped by the support, encouragement, and conversations of those around me. More than anything, this journey has shown me that research is not just about knowledge; it is about people, relationships, and the stories we carry.`,
      ].map((t, i) => <P key={i}>{t}</P>)}

      <div style={{display:'flex', flexDirection:'column', gap:40, marginTop:48}}>

        {[
          {
            name: 'Henry, Wellington & Emerson',
            sub: 'The team that started it all',
            body: `You opened a door for me that I didn't even know I needed. Long before this research began, you gave me my first real glimpse into the tech world, and more than that, you showed me I belonged in it.\n\nThe fact that English wasn't your first language, and that we were all finding our way through the communication gaps, never stopped us. If anything, it taught me something I've carried ever since: connection doesn't require perfection. What matters is the willingness to show up, figure it out together, and keep going.\n\nYou introduced me to a way of working that was warmer and more human than anything I'd known before. We laughed through the hard bits, leaned on each other, and never made it feel like a solo fight. You stretched me, challenged me, and somehow made me believe that a world I once felt completely outside of could actually be mine.\n\nThat season of my life changed the direction of everything. I'll always be grateful for it, and for you.`,
          },
          {
            name: 'Research participants',
            sub: 'Named and anonymous contributors',
            body: `I would like to acknowledge everyone who took the time to listen, share their perspectives, and contribute to this research. Your insights sit at the heart of this work. Every conversation challenged me, inspired me, and reminded me why this research matters. You didn't just contribute to this thesis — you contributed to my growth, both as a researcher and as a person.`,
          },
          {
            name: 'Jade Tang-Taylor',
            sub: 'Academic supervisor',
            body: `Thank you for your patience, guidance, and for backing this project the whole way through, even in the moments I doubted myself. There were times I questioned whether I was good enough or on the right path, and you always brought me back to the work and reminded me that I was. You often reminded me that the self-doubt I was feeling came from how much I cared — and that stayed with me. Your reassurance, honesty, and steady support helped me push through those moments and keep moving forward. Your belief in this project, and in me, has meant more than I can fully put into words.`,
          },
          {
            name: 'Meg Smith',
            sub: 'My mentor and door-opener',
            body: `From the moment we met, you saw something in me that I was still trying to see in myself. Thank you for opening doors, creating opportunities, and encouraging me to step into spaces I might not have walked into on my own. You've challenged me, supported me, and backed me, and I'm so grateful to have you in my corner. You are an incredible wahine, and I feel very fortunate to have your support.`,
          },
          {
            name: 'Dan Te Whenua Walker',
            sub: 'Kaiārahi, trailblazer, and inspirer',
            body: `You have carved a pathway that others can walk with more confidence because of you. Watching you move through the world — with such authenticity, grace, and generosity — has shown me that it is possible to step fully into who you are, honour where you come from, and use that to lift others along the way.\n\nThe framework you shared with me early in this research, "the head and the heart to the puku," became something I carried with me through every interview, every moment of doubt, and every breakthrough. It gave me permission to bring my whole self to this mahi, not just my analytical mind, but my heart and my deep intuition too.\n\nYou lead in a way that makes people feel seen, capable, and brave enough to try. One day, I hope to do the same.`,
          },
          {
            name: 'Shane Burke',
            sub: 'Business mentor and coach',
            body: `Thank you for your consistent support and commitment. You've helped me think bigger about NRX Auaha and what it can become, and you've played a huge role in building my confidence as a leader. You've always pushed me to stop thinking small and step into what's possible.`,
          },
          {
            name: 'Francie Diver',
            sub: 'My amazing auntie',
            body: `Spending time with you at Christmas 2023 and hearing about the work you do inspired me to do more and to be more. When I had the opportunity to have you alongside me on this journey, I jumped at it — thank you for welcoming me into deeper conversations about who we are and where we come from. Having you as part of this research, and as part of my personal journey to reconnect with my whakapapa, has meant more to me than words can express. Your aroha and openness have grounded and guided me throughout this process.`,
          },
          {
            name: 'Faith, Kiia & Skye',
            sub: 'My friends',
            body: `Thank you for always listening to me talk about my nerdy, techy ideas and everything going on in my life outside of dancing. You've pushed me to do more, be more, and think bigger, even when I didn't always see it in myself.`,
          },
          {
            name: 'Marg & Rob',
            sub: 'My anchors',
            body: `There is a particular kind of support that doesn't ask questions or need explaining — it just shows up. That is what you have given me. Throughout this journey, you walked alongside me as I stepped more deeply into my Māori identity, and you never made it feel complicated. You simply held space, with warmth, steadiness, and love. That kind of presence is rare, and it meant more than I can say.`,
          },
          {
            name: 'Christine',
            sub: 'My very first workmate in tech',
            body: `You showed me the ropes and made learning the hard stuff fun while reminding me that we were here to get things done. From problem-solving to laughs along the way, your support meant a lot during those early days. Bestie forever.`,
          },
          {
            name: 'Luke & Stephen',
            sub: 'My ride or die since the age of 11',
            body: `We have been through everything together, and somehow you are still here — still supporting me, still believing in me, and still picking up the phone no matter what. That kind of friendship is rare, and I will never take it for granted.`,
          },
          {
            name: 'Ailsa & Riki',
            sub: 'Mum and brother',
            body: `Thank you for everything you did behind the scenes — the dinners, the school runs, and every time you stepped in to support Xavier so I could keep going. I saw it, and I felt it. I wouldn't have been able to complete this second Master's without you.`,
          },
          {
            name: 'Xavier',
            sub: 'My son',
            body: `You are my why. Everything I do is with you in mind.`,
            accent: true,
          },
        ].map((person) => (
          <div key={person.name} style={{
            display:'grid', gridTemplateColumns:'200px 1fr', gap:32,
            paddingBottom:40, borderBottom:'1px solid var(--hair)',
          }}>
            <div>
              <div style={{fontSize:14, fontWeight:600, color:'var(--ink)', marginBottom:4}}>{person.name}</div>
              {person.sub && <div className="mono" style={{fontSize:10, color:'var(--muted)'}}>{person.sub}</div>}
            </div>
            <div style={{display:'flex', flexDirection:'column', gap:16}}>
              {person.body.split('\n\n').map((para, i) => (
                <p key={i} style={{
                  color: person.accent ? 'var(--ink)' : 'var(--ink-2)',
                  lineHeight:1.8, maxWidth:'none', margin:0,
                  fontStyle: person.accent ? 'italic' : 'normal',
                  fontSize: person.accent ? 'var(--step-lg)' : undefined,
                }}>{para}</p>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div style={{
        marginTop:64, padding:'32px 40px',
        background:'var(--bg-2)', borderRadius:12,
        borderLeft:'3px solid var(--accent)',
      }}>
        <p style={{
          fontFamily:'var(--f-display)', fontSize:'var(--step-lg)',
          fontStyle:'italic', lineHeight:1.6, marginBottom:8, maxWidth:'none', color:'var(--ink)',
        }}>
          He aha te mea nui o te ao? He tangata, he tangata, he tangata.
        </p>
        <p style={{color:'var(--ink-2)', fontSize:13, maxWidth:'none', margin:0}}>
          What is the most important thing in the world? It is people, it is people, it is people.
        </p>
      </div>

      <div style={{marginTop:48}}>
        <P>This mahi brings together two interconnected journeys — my professional path into ethical AI and technology, and my personal journey of reconnecting with my Māori identity and te reo Māori.</P>
        <P>I'm deeply grateful to everyone who has held space for both.</P>
      </div>

      <div style={{marginTop:48}}>
        <img
          src="assets/nadine-xaiver.jpeg"
          alt="Xavier and Nadine"
          style={{
            width:'100%', maxWidth:520, borderRadius:12,
            display:'block',
          }}
        />
        <p className="mono" style={{fontSize:11, color:'var(--muted)', marginTop:12, letterSpacing:'0.08em'}}>
          XAVIER & NADINE
        </p>
      </div>

    </div>
  );
}

function PaywallGate({ setEmailSent, setSentToEmail }) {
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]         = React.useState('');
  const [name, setName]       = React.useState('');
  const [email, setEmail]     = React.useState('');

  const handlePurchase = async () => {
    // Validate name + email before going to Stripe
    if (!name.trim()) { setErr('Please enter your name.'); return; }
    if (!email.trim()) { setErr('Please enter your email address.'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
      setErr('Please enter a valid email address.');
      return;
    }

    setLoading(true);
    setErr('');
    try {
      const res = await fetch('/api/create-checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ product: 'thesis', name: name.trim(), email: email.trim() }),
      });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        setErr(data.error || 'Something went wrong. Please try again.');
        setLoading(false);
      }
    } catch (e) {
      setErr('Could not reach checkout. Please try again.');
      setLoading(false);
    }
  };

  return (
    <div>
      <div style={{position:'relative', overflow:'hidden', borderRadius:12, marginBottom:48}}>
        <div style={{
          padding:'32px 0', filter:'blur(4px)', userSelect:'none', pointerEvents:'none', opacity:0.4,
        }}>
          <h2 style={{marginBottom:24}}>Chapter Two: Literature Review</h2>
          <p style={{lineHeight:1.8, marginBottom:16, maxWidth:'none'}}>
            The field of AI ethics has grown substantially over the past decade, yet the specific intersection of AI and Indigenous language rights remains underexplored. Existing frameworks provide useful scaffolding, but they were largely developed without Indigenous voices at the table.
          </p>
          <p style={{lineHeight:1.8, maxWidth:'none'}}>
            This chapter reviews literature across three intersecting domains: AI bias and language representation; Indigenous data sovereignty frameworks; and Māori-led digital governance initiatives.
          </p>
        </div>
        <div style={{
          position:'absolute', bottom:0, left:0, right:0, height:160,
          background:'linear-gradient(to bottom, transparent, var(--bg))',
        }}/>
      </div>

      <div style={{
        background:'var(--ink)', color:'var(--bg)',
        borderRadius:16, padding:48, textAlign:'center',
        position:'relative', overflow:'hidden',
      }}>
        <div style={{
          position:'absolute', inset:0, pointerEvents:'none',
          backgroundImage:'linear-gradient(rgba(239,230,218,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(239,230,218,0.03) 1px, transparent 1px)',
          backgroundSize:'60px 60px',
        }}/>
        <div style={{position:'relative', zIndex:2}}>
          <div className="label" style={{justifyContent:'center', color:'rgba(239,230,218,0.5)', marginBottom:16}}>Full access</div>
          <div className="display" style={{fontSize:'clamp(3rem,6vw,5rem)', fontStyle:'italic', color:'var(--bg)', marginBottom:8}}>NZ$35</div>
          <p style={{color:'rgba(239,230,218,0.65)', marginBottom:32, fontSize:15, maxWidth:480, margin:'0 auto 32px'}}>
            Unlock all seven chapters, findings, recommendations, appendices, and the full reference list. Lifetime access — read at your own pace.
          </p>
          <div style={{display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap', marginBottom:32}}>
            {['All 7 chapters', 'Findings & themes', 'Recommendations', 'Glossary of te reo', 'Full references', 'Appendices'].map(f => (
              <span key={f} className="mono" style={{
                padding:'6px 12px', border:'1px solid rgba(239,230,218,0.2)',
                borderRadius:999, fontSize:11, color:'rgba(239,230,218,0.7)',
              }}>+ {f}</span>
            ))}
          </div>
          {/* Name + email — required before Stripe checkout */}
          <div style={{
            display:'flex', flexDirection:'column', gap:12,
            maxWidth:400, margin:'0 auto 28px', textAlign:'left',
          }}>
            <div>
              <label style={{display:'block', fontSize:11, color:'rgba(239,230,218,0.5)', letterSpacing:'0.1em', textTransform:'uppercase', marginBottom:6, fontFamily:'monospace'}}>Your name</label>
              <input
                type="text"
                value={name}
                onChange={e => setName(e.target.value)}
                placeholder="e.g. Mere Tūhoe"
                style={{
                  width:'100%', boxSizing:'border-box',
                  padding:'12px 16px', borderRadius:6,
                  border:'1px solid rgba(239,230,218,0.2)',
                  background:'rgba(239,230,218,0.08)',
                  color:'var(--bg)', fontSize:14,
                  outline:'none', fontFamily:'inherit',
                }}
              />
            </div>
            <div>
              <label style={{display:'block', fontSize:11, color:'rgba(239,230,218,0.5)', letterSpacing:'0.1em', textTransform:'uppercase', marginBottom:6, fontFamily:'monospace'}}>Email address</label>
              <input
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="your@email.com"
                style={{
                  width:'100%', boxSizing:'border-box',
                  padding:'12px 16px', borderRadius:6,
                  border:'1px solid rgba(239,230,218,0.2)',
                  background:'rgba(239,230,218,0.08)',
                  color:'var(--bg)', fontSize:14,
                  outline:'none', fontFamily:'inherit',
                }}
              />
              <p style={{fontSize:11, color:'rgba(239,230,218,0.35)', marginTop:6, marginBottom:0, fontFamily:'monospace', letterSpacing:'0.04em'}}>
                YOUR ACCESS LINK WILL BE SENT HERE AFTER PAYMENT
              </p>
            </div>
          </div>

          <button
            onClick={handlePurchase}
            disabled={loading}
            className="btn btn-accent"
            style={{fontSize:15, padding:'16px 32px', opacity: loading ? 0.7 : 1}}
          >
            {loading ? 'Redirecting to checkout…' : 'Purchase full access'} <span className="arrow">→</span>
          </button>
          {err && <p style={{color:'#f5a5a5', marginTop:12, fontSize:13}}>{err}</p>}
          <p className="mono" style={{fontSize:10, color:'rgba(239,230,218,0.3)', marginTop:16, letterSpacing:'0.1em'}}>
            SECURE CHECKOUT · EMAIL ACTIVATION · NO SUBSCRIPTION
          </p>
        </div>
      </div>
    </div>
  );
}

// ─── Unlocked content — fetched from protected API ────────────────────────────

function UnlockedContent({ activeChapter }) {
  const [html, setHtml]       = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]         = React.useState('');

  React.useEffect(() => {
    if (!activeChapter) return;
    setLoading(true); setErr(''); setHtml('');
    const token = localStorage.getItem('thesis_token') || '';
    const url = token
      ? `/api/thesis-chapter?n=${encodeURIComponent(activeChapter)}&token=${encodeURIComponent(token)}`
      : `/api/thesis-chapter?n=${encodeURIComponent(activeChapter)}`;
    fetch(url)
      .then(r => r.json())
      .then(data => {
        if (data.html) { setHtml(data.html); setLoading(false); }
        else { setErr('Could not load this chapter. Please try refreshing.'); setLoading(false); }
      })
      .catch(() => { setErr('Could not load this chapter. Please try refreshing.'); setLoading(false); });
  }, [activeChapter]);

  if (loading) return (
    <div style={{padding:'80px 0', textAlign:'center', color:'var(--muted)'}}>
      <div style={{fontFamily:'monospace', fontSize:12, letterSpacing:'0.1em'}}>LOADING…</div>
    </div>
  );
  if (err) return <p style={{color:'var(--rust,#b84a2b)', padding:'40px 0'}}>{err}</p>;
  if (!html) return null;

  return (
    <div>
      <div style={{
        display:'inline-flex', alignItems:'center', gap:8,
        padding:'8px 16px', background:'var(--bg-2)', border:'1px solid var(--hair)',
        borderRadius:999, marginBottom:48,
      }}>
        <span style={{color:'var(--accent)'}}>✓</span>
        <span className="mono" style={{fontSize:11, color:'var(--ink-2)'}}>Full access granted — use the chapter navigation to read</span>
      </div>
      <div dangerouslySetInnerHTML={{__html: html}} />
    </div>
  );
}

// ─── Chapter content is served by /api/thesis-chapter (see lib/thesis-chapters.js) ─
// Run: node scripts/capture-chapters.js  to regenerate after content changes.


Object.assign(window, { ThesisPage });
