// World Map page with choropleth
// Using a simple natural-earth style via country centroids + squares (no external deps)
// For a proper map we'll draw a world using TopoJSON-free approach: use country dots/tiles arranged grid-style.

const COUNTRY_TILE_POS = {
  "US":         [1,2], "MEXICO":[1,3], "EL SALVADOR":[2,3], "VENEZUELA":[2,4],
  "BRAZIL":     [3,4], "ARGENTINA":[3,5],
  "UK":         [4,1], "SWITZERLAND":[4,2], "ITALY":[5,2], "POLAND":[5,1],
  "UKRAINE":    [6,1], "TURKEY":[6,2], "LEBANON":[6,3], "SAUDI ARABIA":[7,3], "UAE":[8,3],
  "RUSSIA":     [7,0], "CHINA":[9,1], "JAPAN":[11,1], "SOUTH KOREA":[10,1], "HONG KONG":[10,2],
  "PHILIPPINES":[10,3], "INDONESIA":[9,4], "INDIA":[8,2],
  "NIGERIA":    [5,3], "KENYA":[6,4], "SOUTH AFRICA":[5,5],
};

function MapPage({ data, setRoute, embedded }) {
  const { countries, perCountry } = data.summary;
  const [metric, setMetric] = uS('ownCurrent');
  const [hovered, setHovered] = uS(null);
  const [tipPos, setTipPos] = uS(null);
  const [topo, setTopo] = uS(null);
  const stageRef = React.useRef(null);
  const mapCardRef = React.useRef(null);
  const rankRef = React.useRef(null);

  const metrics = MAP_METRICS;

  const vals = perCountry.map(r => r[metric]).filter(v=>typeof v==='number');
  const max = Math.max(...vals);

  // Load d3 + topojson (already in DOM if globe was visited; otherwise inject)
  React.useEffect(() => {
    function loadScript(src) {
      return new Promise((res, rej) => {
        if (document.querySelector(`script[src="${src}"]`)) { res(); return; }
        const s = document.createElement('script');
        s.src = src; s.async = true;
        s.onload = res; s.onerror = rej;
        document.head.appendChild(s);
      });
    }
    (async () => {
      if (!window.d3) await loadScript('https://unpkg.com/d3@7.9.0/dist/d3.min.js');
      if (!window.topojson) await loadScript('https://unpkg.com/topojson-client@3.1.0/dist/topojson-client.min.js');
      // Standalone build uses pre-bundled world atlas; live build fetches from unpkg.
      const url = window.__resources?.worldAtlas || 'https://unpkg.com/world-atlas@2.0.2/countries-110m.json';
      const r = await fetch(url);
      setTopo(await r.json());
    })();
  }, []);

  // Resolve country name from ISO numeric id
  const isoToCountry = React.useMemo(() => {
    const m = {};
    const map = window.COUNTRY_ISO || {};
    for (const c of countries) if (map[c]) m[map[c]] = c;
    return m;
  }, [countries]);

  const valFor = (countryName) => {
    if (!countryName) return null;
    const row = perCountry[countries.indexOf(countryName)];
    return row ? row[metric] : null;
  };

  const colorFor = (countryName) => {
    const v = valFor(countryName);
    if (v == null) return null;
    const t = Math.min(1, v / max);
    return `color-mix(in srgb, var(--brand) ${Math.round(t*90)}%, var(--surface-2))`;
  };

  // Map geometry
  const W = 1100, H = 540;
  let path = null, geo = null, sphere = null, graticule = null, projection = null;
  if (window.d3 && topo && window.topojson) {
    projection = window.d3.geoNaturalEarth1()
      .scale(195)
      .translate([W/2, H/2 + 18]);
    path = window.d3.geoPath(projection);
    geo = window.topojson.feature(topo, topo.objects.countries);
    sphere = { type: 'Sphere' };
    graticule = window.d3.geoGraticule10();
  }

  const onCountryHover = (e, name) => {
    if (!name) { setHovered(null); setTipPos(null); return; }
    const rect = stageRef.current.getBoundingClientRect();
    setHovered(name);
    setTipPos({ x: e.clientX - rect.left, y: e.clientY - rect.top });
  };

  return (
    <section className="section" style={{paddingTop: embedded ? 8 : 56}}>
      <div className="container">
        {!embedded && <div className="eyebrow sans" style={{marginBottom:8}}>World Map · 25 countries</div>}
        <div style={{display:'grid', gridTemplateColumns:'1fr auto', alignItems:'end', gap:32, marginBottom:28}}>
          <h1 style={{maxWidth:'22ch'}}>{metrics.find(m=>m.k===metric).l}<span style={{display:'block', fontFamily:'JetBrains Mono, monospace', fontSize:11, fontWeight:400, textTransform:'uppercase', letterSpacing:'.12em', color:'var(--muted)', marginTop:10}}>{metrics.find(m=>m.k===metric).base}</span></h1>
          <div style={{display:'flex', flexWrap:'wrap', gap:6, maxWidth:520, justifyContent:'flex-end'}}>
            {metrics.map(m => (
              <button key={m.k} onClick={()=>setMetric(m.k)}
                style={{background: m.k===metric?'var(--ink)':'transparent',
                        color: m.k===metric?'var(--paper)':'var(--ink-2)',
                        border:'1px solid var(--rule)', padding:'6px 10px',
                        fontFamily:'JetBrains Mono, monospace', fontSize:10,
                        textTransform:'uppercase', letterSpacing:'.12em', cursor:'pointer'}}>
                {m.l}
              </button>
            ))}
            <ExportButton targetRef={mapCardRef} filename="cbai-map.png" style={{alignSelf:'center'}}/>
          </div>
        </div>

        <div style={{display:'grid', gridTemplateColumns:'1.4fr .6fr', gap:32, alignItems:'start'}}>
        <div className="chart-card" style={{padding:24}} ref={mapCardRef}>
          <div ref={stageRef} style={{position:'relative', width:'100%'}}>
            {!path ?
              <div style={{height:540, display:'flex', alignItems:'center', justifyContent:'center', color:'var(--muted)', fontFamily:'Inter Tight, sans-serif'}}>
                Loading map…
              </div>
              :
              <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%', height:'auto', display:'block'}}>
                {/* Ocean / sphere */}
                <path d={path(sphere)} fill="var(--surface)" stroke="var(--rule)" strokeWidth=".75"/>
                {/* Graticule */}
                <path d={path(graticule)} fill="none" stroke="var(--rule)" strokeWidth=".4" opacity=".5"/>
                {/* Countries */}
                {geo.features.map((feat, fi) => {
                  const iso = String(feat.id).padStart(3, '0');
                  const name = isoToCountry[iso];
                  const inStudy = !!name;
                  const fill = inStudy ? colorFor(name) : null;
                  return (
                    <path key={feat.id || fi}
                      d={path(feat)}
                      style={{
                        fill: inStudy ? (fill || 'var(--surface-2)') : 'var(--surface-2)',
                        stroke: hovered === name ? 'var(--fg)' : 'var(--surface)',
                        strokeWidth: hovered === name ? 1.25 : .4,
                        cursor: inStudy ? 'pointer' : 'default',
                        transition: 'stroke-width 120ms ease',
                      }}
                      onMouseEnter={inStudy ? (e)=>onCountryHover(e, name) : null}
                      onMouseMove={inStudy ? (e)=>onCountryHover(e, name) : null}
                      onMouseLeave={inStudy ? ()=>onCountryHover(null, null) : null}
                    />
                  );
                })}
                {/* Centroid markers — guarantees small countries (HK, Lebanon, El Salvador, UAE) are clickable */}
                {Object.entries(window.COUNTRY_CENTROID || {}).map(([name, ll]) => {
                  if (!countries.includes(name)) return null;
                  const p = projection(ll);
                  if (!p) return null;
                  const v = valFor(name);
                  const isSmall = ['HONG KONG','EL SALVADOR','LEBANON','UAE','SWITZERLAND'].includes(name);
                  if (!isSmall) return null;
                  return (
                    <circle key={name} cx={p[0]} cy={p[1]} r={4}
                      fill={v == null ? 'var(--surface-2)' : 'var(--fg)'}
                      stroke="var(--paper)" strokeWidth={1.2}
                      style={{cursor:'pointer'}}
                      onMouseEnter={(e)=>onCountryHover(e, name)}
                      onMouseMove={(e)=>onCountryHover(e, name)}
                      onMouseLeave={()=>onCountryHover(null, null)}
                    />
                  );
                })}
              </svg>
            }
            {hovered && tipPos &&
              <div style={{
                position:'absolute', left: tipPos.x, top: tipPos.y - 12,
                transform:'translate(-50%, -100%)', pointerEvents:'none',
                background:'var(--surface)', border:'1px solid var(--rule)',
                padding:'8px 12px', fontFamily:'Inter Tight, sans-serif',
                fontSize:13, color:'var(--fg)', boxShadow:'0 6px 24px rgba(0,0,0,.08)',
                whiteSpace:'nowrap', zIndex:10,
              }}>
                <div style={{fontWeight:600}}>{titleCase(hovered)}</div>
                <div style={{fontFamily:'JetBrains Mono, monospace', fontSize:11, color:'var(--ink-2)', marginTop:2}}>
                  {valFor(hovered) == null ? '— (no data)' : fmtPct(valFor(hovered), 0)}
                </div>
              </div>
            }
          </div>

          <div className="map-legend sans" style={{marginTop:20, display:'flex', alignItems:'center', gap:12, justifyContent:'center', fontFamily:'JetBrains Mono, monospace', fontSize:10, color:'var(--muted)', textTransform:'uppercase', letterSpacing:'.12em'}}>
            <span>0%</span>
            <div style={{width:220, height:10, background:'linear-gradient(to right, var(--surface-2), var(--brand))', border:'1px solid var(--rule)'}}/>
            <span>{Math.round(max*100)}%</span>
          </div>
          <p style={{fontFamily:'Inter Tight, sans-serif', fontSize:12, color:'var(--muted)', textAlign:'center', marginTop:14}}>
            Choropleth: countries in the study are colored by {metrics.find(m=>m.k===metric).l.toLowerCase()} ({metrics.find(m=>m.k===metric).base}). Grey = not in study. Hover for exact value.
          </p>
        </div>

        <div className="chart-card" style={{padding:'28px 26px', alignSelf:'start'}}>
          <div className="eyebrow sans" style={{marginBottom:8}}>Ranked by current metric</div>
          <h3 style={{fontFamily:'Source Serif 4, serif', fontSize:18, fontWeight:500, marginBottom:16, textTransform:'none', letterSpacing:'-0.01em'}}>
            {metrics.find(m=>m.k===metric).l}
          </h3>
          {(() => {
            const rows = [...perCountry].filter(r=>typeof r[metric]==='number').sort((a,b)=>b[metric]-a[metric]);
            const list = (arr, muted) =>
              <div style={{display:'grid', gap:4}}>
                {arr.map((r,i)=>
                <div key={r.name} style={{display:'grid', gridTemplateColumns:'24px 1fr 60px', gap:8, alignItems:'baseline', padding:'6px 0'}}>
                  <span className="mono" style={{fontFamily:'JetBrains Mono, monospace', fontSize:10, color:'var(--muted)'}}>{(i+1).toString().padStart(2,'0')}</span>
                  <span style={{fontFamily:'Source Serif 4, serif', fontSize:14, color: muted?'var(--ink-2)':'var(--fg)'}}>{titleCase(r.name)}</span>
                  <span className="mono" style={{fontFamily:'JetBrains Mono, monospace', fontSize:12, textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{fmtPct(r[metric], 0)}</span>
                </div>
                )}
              </div>;
            return (
              <>
                <div className="eyebrow sans" style={{marginBottom:8, color:'var(--brand)'}}>Top 5</div>
                {list(rows.slice(0,5))}
                <div className="eyebrow sans" style={{marginBottom:8, marginTop:22}}>Bottom 5</div>
                {list(rows.slice(-5).reverse(), true)}
                <p style={{fontFamily:'Inter Tight, sans-serif', fontSize:12, color:'var(--muted)', marginTop:20, lineHeight:1.4}}>
                  Full ranking for all 25 countries is below the map.
                </p>
              </>
            );
          })()}
        </div>
        </div>

        <div style={{marginTop:48}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:16, marginBottom:14}}>
            <div className="eyebrow sans">Ranking · {metrics.find(m=>m.k===metric).l}</div>
            <ExportButton targetRef={rankRef} filename="cbai-ranking.png"/>
          </div>
          <div className="chart-card" style={{padding:16}} ref={rankRef}>
            {[...perCountry].sort((a,b)=>(b[metric]||0)-(a[metric]||0)).map((r, i) => (
              <div key={r.name} className="bar-row">
                <div className="lbl sans"><span style={{display:'inline-block', width:24, color:'var(--muted)', fontFamily:'JetBrains Mono, monospace', fontSize:12}}>{i+1}.</span>{titleCase(r.name)}</div>
                <div className="bar-track"><div className="bar-fill" style={{width: ((r[metric]||0)/max*100)+'%'}}/></div>
                <div className="val mono">{fmtPct(r[metric], 0)}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function MethodologyPage() {
  return (
    <section className="section" style={{paddingTop:56}}>
      <div className="section-narrow">
        <div className="eyebrow sans" style={{marginBottom:12}}>Methodology</div>
        <h1 style={{marginBottom:32}}>How the study was conducted</h1>

        <p className="lede sans" style={{fontSize:20, color:'var(--ink-2)', maxWidth:'50ch', marginBottom:40}}>
          A 25-country survey of 25,880 adults, fielded by Morning Consult in partnership
          with the Tech Policy Institute in Cornell University's Jeb E. Brooks School of Public Policy, the Cornell
          Bitcoin Club, the Human
          Rights Foundation and the Reynolds Foundation.
        </p>

        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          We set out to answer a question that attracted plenty of speculation but very little
          hard data: <em>around the world, what does the general public actually know, believe, and do
          about bitcoin?</em> Rather than survey crypto insiders, we asked nationally representative
          samples of adults in 25 countries — bitcoin owners and non-owners alike.
        </p>

        <h2 style={{marginTop:40, marginBottom:16}}>What We Expected to Find</h2>
        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          We began with two working hypotheses. First, that <strong>awareness would far outrun
          understanding</strong> — that most people would recognize bitcoin but few could explain
          how it works. Second, that <strong>belief in bitcoin's usefulness would be strongest
          where the financial system is weakest</strong> — in economies facing inflation, currency
          controls, or limited banking.
        </p>
        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          Both were broadly borne out. Awareness sits near 90% globally while only about one in
          eight can name the 21-million supply limit, and agreement that bitcoin increases
          financial freedom is highest in countries such as Nigeria, Venezuela, and Ukraine. The
          data does not "prove" causation — a survey cannot — but the patterns are consistent and
          hold up across countries.
        </p>

        <h2 style={{marginTop:40, marginBottom:16}}>Quantitative and Qualitative Together</h2>
        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          The study deliberately pairs two kinds of evidence. The <strong>quantitative</strong> core
          measures awareness, ownership, knowledge, and perceptions with closed questions that can be
          weighted and compared across countries. Alongside them, <strong>qualitative</strong>
          questions capture people's own reasons and hesitations — why they bought, why they sold,
          why they never started — so the numbers arrive with the human context behind them.
        </p>

        <h2 style={{marginTop:40, marginBottom:16}}>What This Study Is Not</h2>
        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          To read the findings fairly, it helps to be clear about the study's edges:
        </p>
        <ul style={{color:'var(--ink-2)', marginBottom:16, paddingLeft:22, lineHeight:1.7}}>
          <li>It measures what people <em>say</em> — self-reported knowledge, ownership, and views — not verified wallet balances or on-chain activity.</li>
          <li>It is a snapshot from a single fieldwork window, not a tracker of prices, trading, or how views change over time.</li>
          <li>It is not a forecast. Nothing here predicts bitcoin's future adoption or price.</li>
          <li>It covers the general adult public, not institutional, corporate, or government holdings.</li>
          <li>Questions on current bitcoin ownership were not fielded in China and Hong Kong, due to regulatory constraints there.</li>
        </ul>

        <div style={{background:'var(--surface)', border:'1px solid var(--rule)', borderLeft:'3px solid var(--accent-warm)', padding:'18px 22px', marginBottom:48, fontFamily:'Inter Tight, sans-serif', fontSize:14, color:'var(--ink-2)', maxWidth:'60ch'}}>
          <strong style={{color:'var(--fg)'}}>Data note · final release.</strong> Aggregate estimates shown on the Overview, Aggregate Findings, Country Explorer, and Map
          pages reflect the final post-fielding analytical release (weighted survey means with country fixed-effects for the model section).
          The Question Explorer preserves the original banner crosstabs and may differ at the second-decimal level for some questions.
        </div>

        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:1, background:'var(--rule)', border:'1px solid var(--rule)', marginBottom:48}}>
          {[
            ['Poll ID','2411046'],
            ['Field dates','Dec 16, 2024 – Mar 10, 2025'],
            ['Countries','25'],
            ['Respondents','25,880 adults'],
            ['Fieldwork partner','Morning Consult'],
            ['Margin of error','±2.1% to ±6.2% (by country)'],
          ].map(([k, v]) => (
            <div key={k} style={{background:'var(--surface)', padding:'18px 20px'}}>
              <div className="eyebrow sans" style={{marginBottom:6}}>{k}</div>
              <div style={{fontFamily:'Source Serif 4, serif', fontSize:20}}>{v}</div>
            </div>
          ))}
        </div>

        <h2 style={{marginBottom:16}}>Countries Surveyed</h2>
        <p style={{color:'var(--ink-2)', marginBottom:24}}>
          The sample was designed to span economic, political, and monetary contexts —
          from high-inflation economies to stable reserve-currency holders, from
          countries with wide banking access to those with significant unbanked
          populations.
        </p>

        <div style={{display:'flex', flexWrap:'wrap', gap:6, marginBottom:48}}>
          {Object.keys(COUNTRY_META).map(c => (
            <span key={c} className="chip sans" style={{fontSize:11}}>
              {COUNTRY_META[c].iso3} · {titleCase(c)}
            </span>
          ))}
        </div>

        <h2 style={{marginBottom:16}}>What We Asked</h2>
        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          The questionnaire covered six thematic areas, mapped across 125 individual
          questions including branching logic for owners and non-owners:
        </p>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:1, background:'var(--rule)', border:'1px solid var(--rule)', marginBottom:48}}>
          {[
            ['Awareness & Knowledge','Have you heard of cryptocurrencies, Bitcoin, stablecoins? Can you name Bitcoin\'s 21M supply cap?'],
            ['Ownership & Usage','Do you own bitcoin now, in the past, never? How do you hold it? How often do you transact?'],
            ['Motivations','Why people use Bitcoin: personal freedom, inflation, remittances, curiosity, investment…'],
            ['Trust & Risk','How much do you trust Bitcoin compared to stocks, gold, sovereign currencies?'],
            ['Perceptions','Is Bitcoin volatile, regulated, easy to use? Does it increase financial freedom?'],
            ['Context','Political, financial, and institutional trust; personal finance literacy.'],
          ].map(([k,v]) => (
            <div key={k} style={{background:'var(--surface)', padding:'20px 22px'}}>
              <h3 style={{fontFamily:'Source Serif 4, serif', fontSize:18, fontWeight:500, marginBottom:8, textTransform:'none'}}>{k}</h3>
              <p style={{fontFamily:'Inter Tight, sans-serif', fontSize:13, color:'var(--ink-2)', margin:0}}>{v}</p>
            </div>
          ))}
        </div>

        <h2 style={{marginBottom:16}}>Weighting and Margin of Error</h2>
        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          Samples are weighted by country-specific demographic targets (age, gender,
          region, education). Margins of error are reported per country in the downloaded
          datasets. Unless stated otherwise, percentages shown on this site are weighted.
        </p>

        <h2 style={{marginBottom:16, marginTop:32}}>Data Use and Citation</h2>
        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          Data on this site is freely downloadable per question as CSV. For the full
          banner file, contact the Tech Policy Institute in Cornell University's Jeb E. Brooks School of Public Policy. Morning Consult
          retains copyright on the underlying fieldwork.
        </p>
        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          The machine-readable files behind every chart on this site are also public:
          {' '}<a href="data/summary.json">country-level indicators</a>,
          {' '}<a href="data/aggregate.json">pooled global estimates</a>, and
          {' '}<a href="data/questions.json">all 125 banner questions by country</a>.
        </p>
        <div style={{background:'var(--surface-2)', border:'1px solid var(--rule)', borderLeft:'3px solid var(--brand)', padding:'14px 18px', maxWidth:'72ch'}}>
          <div className="eyebrow sans" style={{marginBottom:8}}>Suggested citation</div>
          <p style={{fontFamily:'Inter Tight, sans-serif', fontSize:13.5, color:'var(--ink-2)', margin:0, lineHeight:1.55}}>
            Tech Policy Institute at Cornell University, <em>Cornell Bitcoin Adoption Index, 2026 Edition</em>.
            Survey of 25,880 adults across 25 countries, fielded December 2024 – March 2025.
          </p>
        </div>
      </div>
    </section>
  );
}

function AboutPage() {
  return (
    <section className="section" style={{paddingTop:56}}>
      <div className="section-narrow">
        <div className="eyebrow sans" style={{marginBottom:12}}>About</div>
        <h1 style={{marginBottom:32}}>The Tech Policy Institute.</h1>

        <p className="lede sans" style={{fontSize:20, color:'var(--ink-2)', maxWidth:'54ch', marginBottom:40}}>
          A research center in Cornell University's Jeb E. Brooks School of Public Policy, studying how
          emerging technologies reshape institutions, markets, and everyday life — and what that
          means for public policy.
        </p>

        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          The Institute brings together economists, technologists, and policy researchers to
          produce independent, evidence-based work on questions that are often long on opinion and
          short on data. Bitcoin is one of those questions. Its supporters describe a tool for
          financial freedom; its critics see risk and hype. What was largely missing was a rigorous,
          global picture of what the public actually thinks.
        </p>
        <p style={{color:'var(--ink-2)', marginBottom:16}}>
          That is why we pursued this study — with the Cornell Bitcoin Club, and with support from
          the Human Rights Foundation and the Reynolds Foundation. Our aim is not to advocate for or
          against bitcoin, but to give researchers, journalists, policymakers, and the public a
          shared, open set of facts to reason from. Detail on how the survey was designed and fielded
          lives on the <a onClick={()=>{window.navTo('methodology');}} style={{color:'var(--brand)', cursor:'pointer'}}>Methodology</a> page.
        </p>

        <h2 style={{marginTop:48, marginBottom:16}}>Partners</h2>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:1, background:'var(--rule)', border:'1px solid var(--rule)'}}>
          {[
            ['Jeb E. Brooks School of Public Policy','https://publicpolicy.cornell.edu/btpi/','Public policy at Cornell University — the institutional home of the Tech Policy Institute.'],
            ['Cornell Bitcoin Club','https://www.cornellbitcoinclub.org/','A registered student organization at Cornell, conducting original research on bitcoin\'s role in society.'],
            ['Human Rights Foundation','https://hrf.org/','Supports the study as part of its work on financial freedom and censorship-resistant money.'],
            ['Reynolds Foundation','https://www.reynoldsfoundation.com/','Funds interdisciplinary research on institutions, trust, and public policy.'],
            ['Morning Consult','https://morningconsult.com/','Fielded the survey across 25 countries between December 2024 and March 2025.'],
          ].map(([k,url,v]) => (
            <a key={k} href={url} target="_blank" rel="noreferrer" style={{background:'var(--surface)', padding:'22px 22px', textDecoration:'none', color:'inherit', display:'block'}}>
              <h3 style={{fontFamily:'Source Serif 4, serif', fontSize:18, fontWeight:500, textTransform:'none', marginBottom:8}}>{k} <span style={{color:'var(--brand)', fontFamily:'JetBrains Mono, monospace', fontSize:12}}>↗</span></h3>
              <p style={{fontFamily:'Inter Tight, sans-serif', fontSize:13, color:'var(--ink-2)', margin:0}}>{v}</p>
            </a>
          ))}
        </div>

        <h2 style={{marginTop:48, marginBottom:16}}>Stay Connected</h2>
        <p style={{color:'var(--ink-2)'}}>
          Press and research inquiries: <a href="mailto:contact@cornellbitcoinclub.org" style={{color:'var(--brand)'}}>contact@cornellbitcoinclub.org</a>
        </p>
      </div>
    </section>
  );
}

const TALKS = [
  {venue:'Bitcoin Japan', date:'November 2025', who:'Ella Hough', slides:'slides/bitcoin-japan-nov2025.pdf'},
  {venue:'Global Bitcoin Summit', date:'October 2025', who:'Ella Hough', slides:'slides/global-bitcoin-summit-oct2025.pdf'},
  {venue:'MIT Digital Currency Initiative', date:'October 2025', who:'Sarah Kreps & Ella Hough', slides:'slides/mit-dci-oct2025.pdf'},
  {venue:'BTC in DC', date:'October 2025', who:'Ella Hough', slides:'slides/btc-in-dc-oct2025.pdf', video:'https://www.youtube.com/watch?v=Z_zH6mS77bs'},
  {venue:'La Casa de Satoshi · Bitcoin 101 Series', date:'September 2025', who:'Ella Hough', slides:'slides/la-casa-de-satoshi-sep2025.pdf'},
  {venue:'Africa Bitcoin Conference Diaspora', date:'August 2025', who:'Ella Hough', slides:'slides/africa-bitcoin-diaspora-aug2025.pdf'},
  {venue:'Bitcoin Policy Institute Summit', date:'July 2025', who:'Sarah Kreps', video:'https://www.youtube.com/watch?v=1M1z94EJMTU'},
  {venue:'What Bitcoin Did', date:'July 2025', who:'Ella Hough', slides:'slides/what-bitcoin-did-jul2025.pdf', video:'https://www.youtube.com/watch?v=q1vUJz2ITaM'},
  {venue:'Oslo Freedom Forum', date:'May 2025', who:'Sarah Kreps', slides:'slides/oslo-freedom-forum-may2025.pdf', video:'https://www.youtube.com/watch?v=pdz43OknQ7A'},
  {venue:'Bitcoin Policy Institute Webinar', date:'April 2025', who:'Sarah Kreps & Ella Hough', slides:'slides/bpi-webinar-apr2025.pdf', video:'https://www.youtube.com/watch?v=7HrnapDSeNk'},
  {venue:'Africa Bitcoin Conference', date:'December 2024', who:'Ella Hough', slides:'slides/africa-bitcoin-conference-dec2024.pdf', video:'https://youtu.be/MI2AzmhwYbw'},
];
const PRESS = [
  {title:'The Technology Behind Financial Freedom: Evidence from a 25-Country Bitcoin Study', outlet:'The National Interest', date:'August 2025', url:'https://nationalinterest.org/blog/techland/the-technology-behind-financial-freedom-evidence-from-a-25-country-bitcoin-study'},
  {title:'BTPI Will Research Relationship Between Bitcoin and Financial Freedom', outlet:'Cornell Chronicle', date:'May 2024', url:'https://news.cornell.edu/stories/2024/05/btpi-will-research-relationship-between-bitcoin-and-financial-freedom'},
];

function TalksMedia() {
  const pill = {fontFamily:'JetBrains Mono, monospace', fontSize:10, textTransform:'uppercase', letterSpacing:'.12em', border:'1px solid var(--rule)', padding:'6px 11px', textDecoration:'none', color:'var(--fg)', whiteSpace:'nowrap'};
  return (
    <div style={{marginTop:72, paddingTop:44, borderTop:'2px solid var(--ink)'}}>
      <div className="eyebrow sans" style={{marginBottom:12}}>Talks & Media</div>
      <h2 style={{marginBottom:14, maxWidth:'24ch'}}>Where We've Presented This Work</h2>
      <p className="sans" style={{fontFamily:'Inter Tight, sans-serif', fontSize:15, color:'var(--ink-2)', maxWidth:'60ch', marginBottom:36}}>
        Slide decks and recordings from conferences, universities, and policy venues where the
        findings were presented. Decks are the versions delivered on the day — figures may predate
        later corrections to the dataset.
      </p>
      <div style={{border:'1px solid var(--rule)', borderBottom:0}}>
        {TALKS.map(t => (
          <div key={t.venue + t.date} style={{display:'grid', gridTemplateColumns:'1fr auto', gap:20, alignItems:'center', padding:'18px 20px', borderBottom:'1px solid var(--rule)', background:'var(--surface)'}}>
            <div>
              <div style={{fontFamily:'Source Serif 4, serif', fontSize:18, marginBottom:5}}>{t.venue}</div>
              <div className="eyebrow sans">{t.date} · {t.who}</div>
            </div>
            <div style={{display:'flex', gap:8, flexWrap:'wrap', justifyContent:'flex-end'}}>
              {t.slides && <a style={pill} href={t.slides} target="_blank" rel="noreferrer">⤓ Slides</a>}
              {t.video && <a style={pill} href={t.video} target="_blank" rel="noreferrer">▶ Watch</a>}
            </div>
          </div>
        ))}
      </div>

      <div className="eyebrow sans" style={{marginTop:56, marginBottom:12}}>In the Press</div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:1, background:'var(--rule)', border:'1px solid var(--rule)'}}>
        {PRESS.map(p => (
          <a key={p.url} href={p.url} target="_blank" rel="noreferrer" style={{background:'var(--surface)', padding:'22px 22px', textDecoration:'none', color:'inherit', display:'block'}}>
            <div className="eyebrow sans" style={{marginBottom:8}}>{p.outlet} · {p.date}</div>
            <div style={{fontFamily:'Source Serif 4, serif', fontSize:18, lineHeight:1.3, marginBottom:10, maxWidth:'30ch'}}>{p.title}</div>
            <div className="eyebrow sans" style={{color:'var(--brand)'}}>Read →</div>
          </a>
        ))}
      </div>
    </div>);
}

function RepositoryPage({ posts }) {
  return (
    <section className="section" style={{paddingTop:56}}>
      <div className="container">
        <div className="eyebrow sans" style={{marginBottom:12}}>Updates · 10-week release series</div>
        <h1 style={{marginBottom:16, maxWidth:'22ch'}}>Every finding, published weekly.</h1>
        <p className="lede sans" style={{fontSize:19, color:'var(--ink-2)', maxWidth:'56ch', marginBottom:20}}>
          Between Week 0 and Week 10, we released the findings of this study as a series
          of thematic analyses — from awareness and ownership to perceptions, trust, and
          catalysts for adoption.
        </p>
        <p className="sans" style={{fontFamily:'Inter Tight, sans-serif', fontSize:14.5, color:'var(--muted)', maxWidth:'62ch', marginBottom:44}}>
          These entries were published week by week as the study rolled out, ahead of the full
          report.
        </p>

        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:1, background:'var(--rule)', border:'1px solid var(--rule)'}}>
          {posts.map(p => (
            <a key={p.slug} href={window.routeHref(p.slug)} onClick={(e)=>{e.preventDefault(); window.navTo(p.slug);}}
               style={{background:'var(--surface)', display:'grid', gridTemplateColumns:'86px 1fr', gap:20, padding:22, textDecoration:'none', color:'inherit'}}>
              <div className="mono" style={{fontFamily:'JetBrains Mono, monospace', fontSize:34, color:'var(--rule)', lineHeight:1, letterSpacing:'-0.03em'}}>
                {String(p.week).padStart(2,'0')}
              </div>
              <div>
                <div className="eyebrow sans" style={{marginBottom:6}}>Week {p.week} · {new Date(p.date).toLocaleDateString('en-US', {month:'short', day:'numeric', year:'numeric'})}</div>
                <h3 style={{fontFamily:'Source Serif 4, serif', fontSize:20, fontWeight:500, textTransform:'none', letterSpacing:'-0.01em', marginBottom:8, maxWidth:'26ch'}}>
                  {p.title}
                </h3>
                <p style={{fontFamily:'Inter Tight, sans-serif', fontSize:13, color:'var(--ink-2)', margin:0, lineHeight:1.45}}>
                  {p.excerpt.slice(0, 180)}{p.excerpt.length>180?'…':''}
                </p>
                <div className="eyebrow sans" style={{marginTop:12, color:'var(--brand)'}}>Read →</div>
              </div>
            </a>
          ))}
        </div>

        <TalksMedia/>
      </div>
    </section>
  );
}

// Combined Map + Globe explorer with a view toggle
function MapGlobePage({ data, setRoute }) {
  return (
    <section className="section" style={{paddingTop:56, paddingBottom:0}}>
      <div className="container">
        <div className="eyebrow sans" style={{marginBottom:8}}>Interactive Globe · 25 countries</div>
        <h1 style={{maxWidth:'20ch', marginBottom:14}}>See it on the world.</h1>
        <p className="sans" style={{fontFamily:'Inter Tight, sans-serif', fontSize:16, color:'var(--ink-2)', maxWidth:'62ch', marginBottom:24}}>
          Choose a measure, then read it geographically. Drag to rotate the globe for a physical sense
          of where adoption clusters. Hover any country for its exact value; click through to its full profile.
        </p>
      </div>
      <GlobePage data={data} embedded/>
    </section>
  );
}

Object.assign(window, { MapPage, MapGlobePage, MethodologyPage, AboutPage, RepositoryPage });
