{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"open-hardback-long-read-article-header-in-ray-marched-morning-sun-on-linen-where-scrolling-turns-a-curling-page-onto-a-gilt-drop-cap","type":"registry:block","title":"Open Hardback Long Read Article Header in Ray Marched Morning Sun on Linen Where Scrolling Turns a Curling Page onto a Gilt Drop Cap","description":"Free React article header: an open hardback on linen in WebGL morning sun. Scroll and one page curls over to reveal a gilt drop cap.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/open-hardback-long-read-article-header-in-ray-marched-morning-sun-on-linen-where-scrolling-turns-a-curling-page-onto-a-gilt-drop-cap.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\nimport { useReducedMotion } from \"framer-motion\";\n\n/** The article this header opens. Everything printed in the book comes from here too. */\nconst article = {\n  kicker: \"Long read\",\n  part: \"Chapter four\",\n  title: \"The Orchard Keeps Its Own Hours\",\n  deck: \"A season with the last grafter on Hensley Lane, who prunes by the light and not by the calendar.\",\n  author: \"Ines Calloway\",\n  minutes: \"14 min read\",\n  book: \"Low Light at Hensley\",\n};\n\n/** Page text. `left` and `front` end the previous chapter, `back` is the epigraph, `opening` starts this one. */\nconst pages = {\n  left: {\n    folio: \"86\",\n    text: \"By the time the frost lifted the yard had gone quiet again, and the ladders leaned where they had been dropped the night before. Nobody spoke of the crop. We swept the packing shed, we oiled the shears, we counted crates that did not need counting. My aunt walked the lower rows twice before breakfast with her hands behind her back, as if she were inspecting soldiers. When she came in she said only that the old Bramleys had held, and that the young trees by the wall would tell us nothing until spring. It was the kind of answer that sounded like comfort and was really a refusal to guess. I have since learned that this is what growers do. They wait in a way that looks like work, and they work in a way that looks like waiting.\",\n  },\n  front: {\n    folio: \"87\",\n    text: \"That night the wind turned round to the west and the kitchen window rattled in its frame until someone wedged a folded letter into the gap. In the morning the sky was the colour of skimmed milk. The last of the windfalls lay brown in the grass, and the starlings had found them. I remember thinking that the year was over, that whatever the orchard had meant to do it had done, and that we would only be clearing up after it now. I was wrong about that, as I was wrong about most things that winter.\",\n  },\n  back: {\n    quote: \"Every tree keeps a calendar of its own. The grafter only learns to read it.\",\n    source: \"from a grafter's notebook, Hensley Lane\",\n  },\n  opening: {\n    text: \"The first cut of the year is made before anyone else is awake. Odile Marchetti carries her saw out at half past six, while the frost still holds the grass stiff, and she does not look at her watch again until noon. She reads the buds instead. A swollen tip on a Cox means one thing, a split scale on a Russet means another, and the difference between them is a week of work. She has done this on the same eleven acres for longer than the farm has had electricity.\",\n  },\n};\n\nconst START_P = 0.68; // where the page hangs in the air when the piece loads\nconst DEMO = [\n  [3.6, 0.68], // seconds held, then the next target\n  [3.4, 1],\n  [2.4, 0],\n  [2.2, 0.68],\n] as const;\n\n// World sizes, shared with the shader.\nconst W = 0.62; // page width\nconst H = 0.44; // half page height (along the table)\nconst F = 2.0; // lens\nconst PW = 640; // atlas pixels per page\nconst PH = Math.round((PW * 2 * H) / W);\nconst SERIF = '\"Iowan Old Style\", \"Palatino Linotype\", Palatino, \"Book Antiqua\", Georgia, serif';\n\nconst VERT = `#version 300 es\nin vec2 aP; void main(){ gl_Position=vec4(aP,0.,1.); }`;\n\nconst FRAG = `#version 300 es\nprecision highp float;\nuniform vec2 uRes; uniform float uTime; uniform vec3 uRo; uniform vec3 uTa; uniform float uShift;\nuniform vec4 uSheet; uniform sampler2D uAtlas;\nout vec4 o;\nconst float W=${W.toFixed(3)}, H=${H.toFixed(3)}, O=0.016, BT=0.009, T=0.03, TH=0.0011, PHA=0.004;\nconst float YB=BT, YT=BT+T, HY=YT+0.0006, PI=3.14159265;\nconst vec3 L=normalize(vec3(-0.35,0.62,-0.7));\nconst vec3 BMIN=vec3(-0.68,-0.01,-0.48), BMAX=vec3(0.68,0.7,0.72);\n\nfloat h21(vec2 p){ p=fract(p*vec2(233.34,851.73)); p+=dot(p,p+23.45); return fract(p.x*p.y); }\nfloat vn(vec2 p){ vec2 i=floor(p),f=fract(p); f=f*f*(3.-2.*f);\n  return mix(mix(h21(i),h21(i+vec2(1,0)),f.x),mix(h21(i+vec2(0,1)),h21(i+vec2(1,1)),f.x),f.y); }\nfloat fbm(vec2 p){ float s=0.,a=.5; for(int i=0;i<4;i++){ s+=a*vn(p); p=p*2.03+7.1; a*=.5; } return s; }\nfloat box2(vec2 p,vec2 b){ vec2 d=abs(p)-b; return length(max(d,0.))+min(max(d.x,d.y),0.); }\nfloat box3(vec3 p,vec3 b){ vec3 d=abs(p)-b; return length(max(d,0.))+min(max(d.x,max(d.y,d.z)),0.); }\nvec2 boxHit(vec3 ro,vec3 rd){ vec3 iv=1./rd; vec3 a=(BMIN-ro)*iv, b=(BMAX-ro)*iv; vec3 n=min(a,b), f=max(a,b);\n  return vec2(max(max(n.x,n.y),n.z), min(min(f.x,f.y),f.z)); }\n\n// the turning leaf: an arc hinged at the gutter that curls back on itself\nvec3 sheetD(vec3 p){\n  float zn=clamp(p.z/H,-1.,1.);\n  float ph=clamp(uSheet.x+uSheet.z*zn,PHA,PI-PHA);\n  float k=uSheet.y*(1.+0.32*zn);\n  k=clamp(k,0.004,max(0.004,2.*(ph-PHA)/W*0.95));\n  vec2 t=vec2(cos(ph),sin(ph)), n=vec2(-t.y,t.x);\n  vec2 q=p.xy-vec2(0.,HY);\n  float r=1./k;\n  vec2 v=vec2(dot(q,t),dot(q,n)+r);\n  float s=-atan(-v.x,v.y)/k;\n  float sc=clamp(s,0.,W), d2;\n  if(s==sc) d2=abs(length(v)-r);\n  else { float tc=-W*k; d2=min(length(v-vec2(0.,r)),length(v-r*vec2(-sin(tc),cos(tc)))); }\n  vec2 w=vec2(d2-TH,abs(p.z)-H);\n  float d=min(max(w.x,w.y),0.)+length(max(w,0.));\n  return vec3(d,sc,length(v)>r?1.:-1.);\n}\nfloat hBlock(float ax){ return YB+T*(1.-0.42*exp(-ax/0.035))-0.003*smoothstep(W-0.025,W,ax); }\n// id: 0 cloth, 1 boards, 2 page blocks, 3 leaf, 4 headband\nvec2 map(vec3 p){\n  vec2 r=vec2(box3(p-vec3(0.,BT*.5,0.),vec3(W+O-0.003,BT*.5-0.0025,H+O-0.003))-0.0025,1.);\n  float ax=abs(p.x);\n  float db=max(max((p.y-hBlock(ax))*0.8,max(ax-W,abs(p.z)-H)),YB-0.002-p.y);\n  if(db<r.x) r=vec2(db,2.);\n  vec3 sd=sheetD(p); if(sd.x<r.x) r=vec2(sd.x,3.);\n  float hb=max(length(vec2(p.x*0.8,p.y-YB-0.012))-0.009,abs(abs(p.z)-H+0.004)-0.005);\n  if(hb<r.x) r=vec2(hb,4.);\n  return r;\n}\nvec3 nor(vec3 p){ vec2 e=vec2(0.0004,-0.0004);\n  return normalize(e.xyy*map(p+e.xyy).x+e.yyx*map(p+e.yyx).x+e.yxy*map(p+e.yxy).x+e.xxx*map(p+e.xxx).x); }\nfloat shadow(vec3 p){\n  vec2 bh=boxHit(p,L); if(bh.x>bh.y||bh.y<0.) return 1.;\n  float s=1., t=max(bh.x,0.003);\n  for(int i=0;i<44;i++){ float h=map(p+L*t).x; s=min(s,16.*h/t); t+=clamp(h,0.002,0.05); if(s<0.01||t>bh.y) break; }\n  return clamp(s,0.,1.);\n}\nfloat ao(vec3 p,vec3 n){ float a=0.,w=1.; for(int i=1;i<=4;i++){ float h=0.008*float(i)*float(i); a+=w*(h-map(p+n*h).x); w*=.6; } return clamp(1.-a*8.,0.,1.); }\n// morning sun through a window with a cross bar and a tree outside\nfloat sun(vec3 p){\n  vec2 w=(p+L*((2.4-p.y)/L.y)).xz-vec2(-2.2,-3.31);\n  float bl=0.05+0.02*fbm(w*3.);\n  float m=smoothstep(bl,-bl,box2(w,vec2(1.62,1.25)));\n  vec2 g=abs(w); m*=smoothstep(0.02,0.02+bl,g.x)*smoothstep(0.018,0.018+bl,g.y);\n  float lv=fbm(w*2.2+vec2(uTime*0.04,sin(uTime*0.27)*0.05));\n  m*=mix(0.3,1.,smoothstep(0.34,0.56,lv+0.1*(w.x+1.2)));\n  return m;\n}\nvec3 env(vec3 d){\n  vec3 c=mix(vec3(0.3,0.27,0.24),vec3(0.66,0.64,0.6),smoothstep(-0.2,0.7,d.y));\n  c+=vec3(3.4,2.8,2.0)*pow(max(dot(d,L),0.),18.);\n  return c;\n}\nvec4 ink(float idx,vec2 uv){ return texture(uAtlas,vec2((idx+clamp(uv.x,0.,1.))*0.25,clamp(uv.y,0.,1.)),-0.9); }\nvoid main(){\n  vec2 uv=(gl_FragCoord.xy-0.5*uRes)/uRes.y; uv.y+=uShift;\n  vec3 fw=normalize(uTa-uRo), rt=normalize(cross(fw,vec3(0,1,0))), up=cross(rt,fw);\n  vec3 rd=normalize(fw*${F.toFixed(2)}+rt*uv.x+up*uv.y), ro=uRo;\n  float tp=-ro.y/rd.y; if(tp<0.) tp=1e3;\n  float t=tp, id=0.; bool hit=false;\n  vec2 bh=boxHit(ro,rd);\n  if(bh.x<bh.y && bh.y>0.){\n    float tt=max(bh.x,0.), te=min(bh.y,tp);\n    for(int i=0;i<110;i++){ vec2 h=map(ro+rd*tt); if(h.x<0.00012*tt){ hit=true; id=h.y; break; } tt+=h.x*0.7; if(tt>te) break; }\n    if(hit) t=tt;\n  }\n  vec3 p=ro+rd*t;\n  vec3 n= hit ? nor(p) : vec3(0.,1.,0.);\n  float fp=t/(uRes.y*${F.toFixed(2)});\n  vec3 alb; float rough=0.9, spec=0.04, metal=0., trans=0.;\n  vec3 sunC=vec3(1.0,0.8,0.55)*2.0;\n  if(!hit){\n    // linen: slubbed weave, ironed fold lines, detail fading with distance\n    vec2 c=p.xz;\n    float fade=smoothstep(0.0045,0.0016,fp);\n    float sx=fbm(vec2(c.x*30.,c.y*3.)), sz=fbm(vec2(c.x*3.,c.y*30.)+5.);\n    float tx=sin(c.x*430.+sx*5.), tz=sin(c.y*430.+sz*5.);\n    float cross_=step(0.,sin(c.x*215.+sx*2.5)*sin(c.y*215.+sz*2.5));\n    float wv=mix(tz*tz,tx*tx,cross_);\n    float slub=fbm(vec2(c.x*8.,c.y*90.))*0.5+fbm(vec2(c.x*90.,c.y*8.))*0.5;\n    alb=vec3(0.66,0.6,0.5)*(0.9+0.1*fbm(c*5.))*(1.-fade*(0.12*(1.-wv)+0.08*(slub-0.5)));\n    float fx=c.x+0.98, fz=c.y+0.78;\n    float gx=-2.*fx/0.0009*exp(-fx*fx/0.0009)*0.0018, gz=-2.*fz/0.0012*exp(-fz*fz/0.0012)*0.0016;\n    n=normalize(vec3(-gx-fade*0.05*(tx*cos(c.x*430.)),1.,-gz-fade*0.05*tz*cos(c.y*430.)));\n    rough=0.95;\n  } else if(id<1.5){\n    // cloth over the boards\n    float wv=fbm(p.xz*vec2(300.,40.))*0.5+fbm(p.xz*vec2(40.,300.))*0.5;\n    alb=vec3(0.13,0.2,0.19)*(0.85+0.3*wv); rough=0.8; spec=0.05;\n  } else if(id<2.5){\n    if(n.y>0.55 && p.y>YB+T*0.4){\n      float ax=abs(p.x), fib=fbm(p.xz*170.)*0.5+fbm(p.xz*24.)*0.5;\n      alb=vec3(0.88,0.83,0.73)*(0.95+0.07*fib);\n      vec2 cock=vec2(fbm(p.xz*9.),fbm(p.xz*9.+4.))-0.5; n=normalize(n+vec3(cock.x,0.,cock.y)*0.05);\n      vec4 k= p.x<0. ? ink(0.,vec2((p.x+W)/W,(p.z+H)/(2.*H))) : ink(3.,vec2(p.x/W,(p.z+H)/(2.*H)));\n      float gilt=k.a*step(0.5,k.r)*step(0.34,k.g)*step(k.b,0.3);\n      alb=mix(alb,k.rgb*0.7,min(1.,k.a*1.15));\n      if(gilt>0.5){ alb=vec3(0.78,0.5,0.15); metal=1.; rough=0.22+0.25*fbm(p.xz*500.); }\n      rough=max(rough*(1.-metal),metal>0.5?rough:0.85);\n    } else {\n      float st=fbm(vec2(p.y*2200.,(p.x+p.z)*6.));\n      alb=vec3(0.9,0.85,0.74)*(0.86+0.18*st); rough=0.9;\n    }\n  } else if(id<3.5){\n    vec3 sd=sheetD(p);\n    float u=sd.y/W, v=(p.z+H)/(2.*H);\n    float fib=fbm(vec2(u*W,p.z)*170.)*0.5+fbm(vec2(u*W,p.z)*24.)*0.5;\n    alb=vec3(0.89,0.84,0.74)*(0.95+0.07*fib); rough=0.85;\n    bool front=sd.z>0.;\n    vec4 k= front ? ink(1.,vec2(u,v)) : ink(2.,vec2(1.-u,v));\n    vec4 kb= front ? ink(2.,vec2(1.-u,v)) : ink(1.,vec2(u,v));\n    trans=1.;\n    alb=mix(alb,alb*0.82,kb.a*0.12);\n    alb=mix(alb,k.rgb*0.7,min(1.,k.a*1.15));\n    if(dot(n,L)<0.) alb=mix(alb,alb*0.45,kb.a*0.75);\n  } else {\n    float s=step(0.5,fract(p.x*300.+p.y*300.));\n    alb=mix(vec3(0.5,0.1,0.08),vec3(0.86,0.8,0.66),s); rough=0.6;\n  }\n  float sm=sun(p), oc=1.;\n  vec3 pp=p+n*0.0012;\n  if(p.x>BMIN.x-0.12 && p.x<BMAX.x+0.12 && p.z>BMIN.z-0.12 && p.z<BMAX.z+0.1) oc=ao(p,n);\n  float dl=dot(n,L), sh, tr=0.;\n  if(trans>0.5 && dl<0.){ sh=shadow(p-n*0.0025); tr=-dl*sh*sm; dl=0.; }\n  else { sh= dl>0. ? shadow(pp) : 0.; dl=max(dl,0.); }\n  vec3 amb=vec3(0.27,0.26,0.26)*(0.55+0.45*n.y)*oc;\n  vec3 bounce=vec3(0.45,0.33,0.2)*0.45*oc*clamp(0.5-0.5*n.y,0.,1.);\n  vec3 dif=alb*(sunC*dl*sh*sm+amb+bounce);\n  if(trans>0.5) dif+=alb*vec3(1.,0.86,0.66)*sunC*tr*0.42;\n  vec3 r=reflect(rd,n), hv=normalize(L-rd);\n  float fr=0.04+0.96*pow(1.-max(dot(n,-rd),0.),5.);\n  float g=pow(max(dot(n,hv),0.),2./(rough*rough*rough+0.002))*(1./(rough*rough*2.+0.2));\n  vec3 col;\n  if(metal>0.5) col=alb*(env(r)*0.3*oc+sunC*g*sh*sm*0.9+sunC*dl*sh*sm*0.35)+alb*amb*0.25;\n  else col=dif+spec*(fr*env(r)*0.3*oc+sunC*g*sh*sm*0.12);\n  // morning haze toward the back of the room\n  col=mix(col,vec3(0.62,0.58,0.52),smoothstep(2.5,6.,t)*0.2);\n  col*=1.0-0.24*dot(uv*vec2(0.75,1.),uv*vec2(0.75,1.));\n  col=(col*(2.51*col+0.03))/(col*(2.43*col+0.59)+0.14);\n  col=pow(clamp(col,0.,1.),vec3(1./2.2));\n  col=mix(col,col*col*(3.-2.*col),0.35);\n  col+=(h21(gl_FragCoord.xy+fract(uTime)*91.)-0.5)*0.02;\n  o=vec4(col,1.);\n}`;\n\nfunction lines(ctx: CanvasRenderingContext2D, text: string, max: number, firstIndent = 0, narrow?: { lines: number; by: number }) {\n  const out: { words: string[]; w: number; last: boolean; indent: number }[] = [];\n  let cur: string[] = [];\n  const width = (i: number) => max - (i === 0 ? firstIndent : 0) - (narrow && i < narrow.lines ? narrow.by : 0);\n  for (const word of text.split(\" \")) {\n    const next = [...cur, word].join(\" \");\n    if (ctx.measureText(next).width > width(out.length) && cur.length) {\n      out.push({ words: cur, w: width(out.length), last: false, indent: max - width(out.length) });\n      cur = [word];\n    } else cur.push(word);\n  }\n  if (cur.length) out.push({ words: cur, w: width(out.length), last: true, indent: max - width(out.length) });\n  return out;\n}\n\n/** Sets justified text, the way a book is set. */\nfunction setBody(g: CanvasRenderingContext2D, text: string, x: number, y: number, max: number, lead: number, opts: { indent?: number; narrow?: { lines: number; by: number } } = {}) {\n  const ls = lines(g, text, max, opts.indent ?? 0, opts.narrow);\n  ls.forEach((l, i) => {\n    const x0 = x + l.indent;\n    if (l.last || l.words.length < 2) {\n      g.fillText(l.words.join(\" \"), x0, y + i * lead);\n      return;\n    }\n    const wordsW = l.words.reduce((s, w) => s + g.measureText(w).width, 0);\n    const gap = (l.w - wordsW) / (l.words.length - 1);\n    let cx = x0;\n    l.words.forEach((w) => {\n      g.fillText(w, cx, y + i * lead);\n      cx += g.measureText(w).width + gap;\n    });\n  });\n  return y + ls.length * lead;\n}\n\n/** Prints the four pages into one texture: left page, leaf front, leaf back, chapter opening. */\nfunction makeAtlas() {\n  const c = document.createElement(\"canvas\");\n  c.width = PW * 4;\n  c.height = PH;\n  const g = c.getContext(\"2d\")!;\n  const ink = \"rgb(24,19,16)\";\n  const red = \"rgb(128,46,34)\";\n  const gilt = \"rgb(196,140,46)\";\n  const top = 92;\n  const body = 21;\n  const lead = 31;\n  const head = (x0: number, label: string, folio: string, verso: boolean) => {\n    g.fillStyle = ink;\n    g.font = `500 13px ${SERIF}`;\n    g.letterSpacing = \"3px\";\n    g.textAlign = \"center\";\n    g.fillText(label.toUpperCase(), x0 + PW / 2, 56);\n    g.letterSpacing = \"0px\";\n    g.font = `400 16px ${SERIF}`;\n    g.fillText(folio, x0 + (verso ? 70 : PW - 70), PH - 44);\n    g.textAlign = \"left\";\n  };\n  // 0: left page (verso)\n  let x0 = 0;\n  head(x0, article.book, pages.left.folio, true);\n  g.fillStyle = ink;\n  g.font = `500 ${body}px ${SERIF}`;\n  setBody(g, pages.left.text, x0 + 66, top + 20, PW - 66 - 54, lead, { indent: 26 });\n  // 1: leaf front (recto)\n  x0 = PW;\n  head(x0, \"The long frost\", pages.front.folio, false);\n  g.fillStyle = ink;\n  g.font = `500 ${body}px ${SERIF}`;\n  const end = setBody(g, pages.front.text, x0 + 54, top + 20, PW - 54 - 66, lead, { indent: 26 });\n  g.fillStyle = red;\n  [-18, 0, 18].forEach((dx) => {\n    g.beginPath();\n    g.arc(x0 + PW / 2 + dx, end + 40, dx === 0 ? 4 : 3, 0, Math.PI * 2);\n    g.fill();\n  });\n  // 2: leaf back (verso): epigraph\n  x0 = PW * 2;\n  g.fillStyle = ink;\n  g.textAlign = \"center\";\n  g.font = `italic 400 27px ${SERIF}`;\n  const qs = lines(g, pages.back.quote, PW - 200);\n  qs.forEach((l, i) => g.fillText(l.words.join(\" \"), x0 + PW / 2, PH * 0.34 + i * 40));\n  g.font = `400 14px ${SERIF}`;\n  g.letterSpacing = \"2.5px\";\n  g.fillStyle = red;\n  g.fillText(pages.back.source.toUpperCase(), x0 + PW / 2, PH * 0.34 + qs.length * 40 + 30);\n  g.letterSpacing = \"0px\";\n  g.font = `400 16px ${SERIF}`;\n  g.fillStyle = ink;\n  g.fillText(\"88\", x0 + 70, PH - 44);\n  g.textAlign = \"left\";\n  // 3: chapter opening (recto) with a gilt drop cap\n  x0 = PW * 3;\n  g.textAlign = \"center\";\n  g.fillStyle = red;\n  g.font = `500 15px ${SERIF}`;\n  g.letterSpacing = \"6px\";\n  g.fillText(article.part.toUpperCase(), x0 + PW / 2, 150);\n  g.letterSpacing = \"0px\";\n  g.fillStyle = ink;\n  g.font = `italic 400 38px ${SERIF}`;\n  const ts = lines(g, article.title, PW - 170);\n  ts.forEach((l, i) => g.fillText(l.words.join(\" \"), x0 + PW / 2, 214 + i * 46));\n  const ruleY = 214 + ts.length * 46 + 6;\n  g.fillRect(x0 + PW / 2 - 28, ruleY, 56, 1.5);\n  g.textAlign = \"left\";\n  const by = ruleY + 74;\n  const capLines = 4;\n  g.fillStyle = gilt;\n  g.font = `600 ${lead * capLines + 6}px ${SERIF}`;\n  const cap = pages.opening.text[0];\n  g.fillText(cap, x0 + 54, by + lead * (capLines - 1) + 2);\n  const capW = g.measureText(cap).width + 14;\n  g.fillStyle = ink;\n  g.font = `500 ${body}px ${SERIF}`;\n  setBody(g, pages.opening.text.slice(1), x0 + 54, by, PW - 54 - 66, lead, { narrow: { lines: capLines, by: capW } });\n  g.font = `400 16px ${SERIF}`;\n  g.textAlign = \"center\";\n  g.fillText(\"89\", x0 + PW / 2, PH - 44);\n  g.textAlign = \"left\";\n  return c;\n}\n\n/** Turns page progress into the leaf's hinge angle, curl and twist. */\nfunction leaf(p: number, v: number, time: number) {\n  const a = Math.sin(Math.PI * Math.min(1, Math.max(0, p)));\n  const phi = 0.004 + (Math.PI - 0.008) * Math.min(1, Math.max(0, p)) + 0.03 * Math.sin(time * 1.15) * a;\n  const k = 0.004 + 1.95 * Math.pow(a, 1.15) + Math.max(-0.6, Math.min(1.3, 0.9 * v));\n  const tw = 0.3 * a + Math.max(-0.2, Math.min(0.25, 0.12 * v)) + 0.02 * Math.sin(time * 0.8) * a;\n  return [phi, k, tw, 0];\n}\n\nfunction camera(aspect: number) {\n  const ta = [0.0, 0.06, 0.04];\n  const dir = [0.42, 1.0, 1.0];\n  const len = Math.hypot(dir[0], dir[1], dir[2]);\n  const fitW = 1.3;\n  const D = Math.max((fitW * F) / (0.5 * aspect), 4.05);\n  const ro = ta.map((v, k) => v + (dir[k] / len) * D);\n  const shift = aspect < 0.9 ? 0.3 : 0.235;\n  return { ro, ta, shift };\n}\n\nexport default function OpenHardbackArticleHeader() {\n  const reduce = useReducedMotion();\n  const [webgl, setWebgl] = useState(true);\n  const [turned, setTurned] = useState(false);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const rootRef = useRef<HTMLElement>(null);\n  const targetRef = useRef<number>(START_P);\n  const userRef = useRef(false);\n  const pokeRef = useRef<() => void>(() => {});\n\n  const turn = () => {\n    userRef.current = true;\n    const next = targetRef.current < 0.5 ? 1 : 0;\n    targetRef.current = next;\n    setTurned(next === 1);\n    pokeRef.current();\n  };\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    const root = rootRef.current;\n    if (!canvas || !root) return;\n    const gl = canvas.getContext(\"webgl2\", { antialias: false, alpha: false, powerPreference: \"high-performance\" });\n    if (!gl) {\n      setWebgl(false);\n      return;\n    }\n    const sh = (type: number, src: string) => {\n      const s = gl.createShader(type)!;\n      gl.shaderSource(s, src);\n      gl.compileShader(s);\n      if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s) || \"shader\");\n      return s;\n    };\n    let prog: WebGLProgram;\n    try {\n      prog = gl.createProgram()!;\n      gl.attachShader(prog, sh(gl.VERTEX_SHADER, VERT));\n      gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, FRAG));\n      gl.linkProgram(prog);\n      if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog) || \"link\");\n    } catch (e) {\n      console.warn(e);\n      setWebgl(false);\n      return;\n    }\n    gl.useProgram(prog);\n    const buf = gl.createBuffer();\n    gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n    const loc = gl.getAttribLocation(prog, \"aP\");\n    gl.enableVertexAttribArray(loc);\n    gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);\n    const tex = gl.createTexture();\n    gl.bindTexture(gl.TEXTURE_2D, tex);\n    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, makeAtlas());\n    gl.generateMipmap(gl.TEXTURE_2D);\n    const aniso = gl.getExtension(\"EXT_texture_filter_anisotropic\");\n    if (aniso) gl.texParameterf(gl.TEXTURE_2D, aniso.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(8, gl.getParameter(aniso.MAX_TEXTURE_MAX_ANISOTROPY_EXT)));\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n    const U = (n: string) => gl.getUniformLocation(prog, n);\n    const uRes = U(\"uRes\"), uTime = U(\"uTime\"), uRo = U(\"uRo\"), uTa = U(\"uTa\"), uShift = U(\"uShift\"), uSheet = U(\"uSheet\");\n    gl.uniform1i(U(\"uAtlas\"), 0);\n\n    // page state: progress p (0 lying right, 1 lying left) and its speed\n    const st = { p: reduce ? 1 : START_P, v: 0 };\n    if (reduce) targetRef.current = 1;\n    let scale = 1;\n    let w = 0, h = 0, aspect = 16 / 9;\n    let lastT = 0;\n    const draw = (time: number) => {\n      const cam = camera(aspect);\n      gl.uniform2f(uRes, w, h);\n      gl.uniform1f(uTime, time);\n      gl.uniform3fv(uRo, cam.ro);\n      gl.uniform3fv(uTa, cam.ta);\n      gl.uniform1f(uShift, cam.shift);\n      gl.uniform4fv(uSheet, leaf(st.p, st.v, reduce ? 0 : time));\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n    };\n    const resize = () => {\n      const r = canvas.getBoundingClientRect();\n      const dpr = Math.min(window.devicePixelRatio || 1, 1.5);\n      const k = Math.min(dpr * scale, Math.sqrt(1.5e6 / Math.max(1, r.width * r.height)));\n      w = Math.max(2, Math.round(r.width * k));\n      h = Math.max(2, Math.round(r.height * k));\n      canvas.width = w;\n      canvas.height = h;\n      aspect = r.width / Math.max(1, r.height);\n      gl.viewport(0, 0, w, h);\n      draw(lastT);\n    };\n\n    // the idle demo: hold the leaf in the air, let it land, turn it back\n    let demoAt = performance.now() / 1000;\n    let demoI = 0;\n    const step = (dt: number, time: number) => {\n      if (!userRef.current && time - demoAt > DEMO[demoI][0]) {\n        demoAt = time;\n        demoI = (demoI + 1) % DEMO.length;\n        targetRef.current = DEMO[demoI][1];\n      }\n      const tgt = targetRef.current;\n      // paper is light: a soft spring with air drag, and it lands with a small bounce\n      const acc = 13 * (tgt - st.p) - 4.6 * st.v;\n      st.v += acc * dt;\n      st.p += st.v * dt;\n      if (st.p > 1) {\n        st.p = 1;\n        if (st.v > 0) st.v *= -0.22;\n      }\n      if (st.p < 0) {\n        st.p = 0;\n        if (st.v < 0) st.v *= -0.22;\n      }\n    };\n\n    let raf = 0;\n    let visible = true;\n    let prev = performance.now();\n    let frames = 0, fpsT = prev, slow = 0;\n    const loop = (now: number) => {\n      raf = 0;\n      const dt = Math.min(0.05, (now - prev) / 1000);\n      prev = now;\n      lastT = now / 1000;\n      const sub = Math.ceil(dt / (1 / 240));\n      for (let i = 0; i < sub; i++) step(dt / sub, lastT);\n      draw(lastT);\n      frames++;\n      if (now - fpsT > 1000) {\n        const fps = (frames * 1000) / (now - fpsT);\n        canvas.dataset.fps = fps.toFixed(1);\n        if (fps < 40 && scale > 0.55) {\n          slow++;\n          if (slow >= 2) {\n            scale = Math.max(0.55, scale - 0.15);\n            slow = 0;\n            resize();\n          }\n        } else slow = 0;\n        frames = 0;\n        fpsT = now;\n      }\n      if (visible) raf = requestAnimationFrame(loop);\n    };\n    const start = () => {\n      if (reduce) return;\n      if (!raf && visible) {\n        prev = performance.now();\n        raf = requestAnimationFrame(loop);\n      }\n    };\n    pokeRef.current = () => {\n      if (reduce) {\n        st.p = targetRef.current;\n        st.v = 0;\n        draw(lastT);\n      } else start();\n    };\n\n    // scrolling over the header turns the leaf: down turns it over, up brings it back\n    const nudge = (dy: number) => {\n      if (reduce) return;\n      userRef.current = true;\n      const t = Math.max(0, Math.min(1, targetRef.current + dy / 650));\n      targetRef.current = t;\n      setTurned(t > 0.5);\n    };\n    let lastY = window.scrollY;\n    let wheelAt = 0;\n    const onScroll = () => {\n      const y = window.scrollY;\n      if (performance.now() - wheelAt > 120) {\n        const r = root.getBoundingClientRect();\n        if (r.bottom > 0 && r.top < window.innerHeight) nudge(y - lastY);\n      }\n      lastY = y;\n    };\n    const onWheel = (e: WheelEvent) => {\n      wheelAt = performance.now();\n      nudge(e.deltaY);\n    };\n    let touchY = 0;\n    const onTouchStart = (e: TouchEvent) => {\n      touchY = e.touches[0].clientY;\n    };\n    const onTouchMove = (e: TouchEvent) => {\n      const y = e.touches[0].clientY;\n      wheelAt = performance.now();\n      nudge((touchY - y) * 1.4);\n      touchY = y;\n    };\n    window.addEventListener(\"scroll\", onScroll, { passive: true });\n    root.addEventListener(\"wheel\", onWheel, { passive: true });\n    root.addEventListener(\"touchstart\", onTouchStart, { passive: true });\n    root.addEventListener(\"touchmove\", onTouchMove, { passive: true });\n\n    const ro = new ResizeObserver(resize);\n    ro.observe(canvas);\n    resize();\n    const io = new IntersectionObserver(([e]) => {\n      visible = e.isIntersecting && !document.hidden;\n      if (visible) start();\n    });\n    io.observe(canvas);\n    const onVis = () => {\n      visible = !document.hidden;\n      if (visible) start();\n    };\n    document.addEventListener(\"visibilitychange\", onVis);\n    start();\n    return () => {\n      cancelAnimationFrame(raf);\n      ro.disconnect();\n      io.disconnect();\n      document.removeEventListener(\"visibilitychange\", onVis);\n      window.removeEventListener(\"scroll\", onScroll);\n      root.removeEventListener(\"wheel\", onWheel);\n      root.removeEventListener(\"touchstart\", onTouchStart);\n      root.removeEventListener(\"touchmove\", onTouchMove);\n      pokeRef.current = () => {};\n      gl.deleteTexture(tex);\n      gl.deleteBuffer(buf);\n      gl.deleteProgram(prog);\n    };\n  }, [reduce]);\n\n  return (\n    <header ref={rootRef} className=\"relative isolate min-h-[680px] overflow-hidden bg-[#c9c0b0] text-[#221c17] sm:min-h-[780px]\">\n      {webgl ? (\n        <canvas ref={canvasRef} aria-hidden=\"true\" className=\"absolute inset-0 -z-10 h-full w-full\" />\n      ) : (\n        <StillBook />\n      )}\n      <div className=\"mx-auto flex max-w-5xl flex-col items-center px-4 pt-12 text-center sm:px-6 sm:pt-14\">\n        <p className=\"flex items-center gap-3 text-[11px] font-semibold uppercase tracking-[0.28em] text-[#6e2a1f] sm:text-[12px]\">\n          <span>{article.kicker}</span>\n          <span aria-hidden=\"true\" className=\"h-px w-6 bg-[#6e2a1f]/60\" />\n          <span>{article.part}</span>\n        </p>\n        <h2\n          className=\"mt-4 max-w-4xl text-balance text-[44px] leading-[0.95] tracking-[-0.025em] sm:text-[68px] lg:text-[84px]\"\n          style={{ fontFamily: SERIF, fontWeight: 500 }}\n        >\n          {article.title}\n        </h2>\n        <p className=\"mt-5 max-w-xl text-[16px] leading-relaxed text-[#3d342c] sm:text-[18px]\" style={{ fontFamily: SERIF, fontStyle: \"italic\" }}>\n          {article.deck}\n        </p>\n        <p className=\"mt-4 text-[12px] font-medium uppercase tracking-[0.2em] text-[#4a4037]\" style={{ fontFamily: '\"Inter Tight\", \"Inter\", ui-sans-serif, system-ui' }}>\n          By {article.author} <span aria-hidden=\"true\">·</span> {article.minutes}\n        </p>\n      </div>\n      <div className=\"absolute inset-x-0 bottom-5 flex items-center justify-center gap-4 px-4 sm:justify-end sm:px-8\">\n        <span aria-hidden=\"true\" className=\"hidden text-[12px] tracking-[0.06em] text-[#3d342c] sm:inline\" style={{ fontFamily: SERIF, fontStyle: \"italic\" }}>\n          or scroll to turn it\n        </span>\n        <button\n          type=\"button\"\n          onClick={turn}\n          aria-pressed={turned}\n          className=\"min-h-[44px] rounded-full bg-[#221c17]/85 px-5 text-[13px] font-medium tracking-[0.04em] text-[#f3ece0] shadow-[0_8px_24px_-10px_rgba(30,20,10,0.6)] backdrop-blur-sm transition-colors hover:bg-[#221c17] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#f3ece0] focus-visible:ring-offset-2 focus-visible:ring-offset-[#221c17]\"\n          style={{ fontFamily: '\"Inter Tight\", \"Inter\", ui-sans-serif, system-ui' }}\n        >\n          {turned ? \"Turn back a page\" : \"Turn the page\"}\n        </button>\n      </div>\n      <div className=\"sr-only\">\n        <p>{pages.back.quote} ({pages.back.source})</p>\n        <p>{pages.opening.text}</p>\n      </div>\n    </header>\n  );\n}\n\n/** Shown without WebGL 2: the open book in still light, set in real type. */\nfunction StillBook() {\n  return (\n    <div\n      className=\"absolute inset-0 -z-10\"\n      style={{\n        background:\n          \"radial-gradient(ellipse 70% 55% at 38% 78%, rgba(255,236,200,0.55), transparent 70%), repeating-linear-gradient(0deg, rgba(90,70,50,0.05) 0 1px, transparent 1px 4px), repeating-linear-gradient(90deg, rgba(90,70,50,0.05) 0 1px, transparent 1px 4px), #c9c0b0\",\n      }}\n    >\n      <div className=\"absolute bottom-[12%] left-1/2 w-[min(80%,500px)] -translate-x-1/2 [perspective:1100px]\">\n        <div\n          className=\"grid grid-cols-2 rounded-[3px] bg-[#22332f] p-[6px] shadow-[18px_26px_30px_-12px_rgba(50,35,20,0.5)]\"\n          style={{ transform: \"rotateX(38deg) rotateZ(-6deg)\" }}\n        >\n          {[0, 1].map((i) => (\n            <div\n              key={i}\n              className=\"aspect-[0.7] overflow-hidden bg-[#f1e9d8] p-[7%] text-justify text-[5px] leading-[1.45] text-[#2a231d] sm:text-[7px]\"\n              style={{\n                fontFamily: SERIF,\n                backgroundImage: i === 0 ? \"linear-gradient(90deg, transparent 80%, rgba(80,60,40,0.22))\" : \"linear-gradient(270deg, transparent 80%, rgba(80,60,40,0.22))\",\n              }}\n            >\n              {i === 0 ? (\n                <p>{pages.left.text}</p>\n              ) : (\n                <p>\n                  <span className=\"float-left mr-1 text-[3.4em] leading-[0.8] text-[#b0812f]\">{pages.opening.text[0]}</span>\n                  {pages.opening.text.slice(1)}\n                </p>\n              )}\n            </div>\n          ))}\n        </div>\n      </div>\n    </div>\n  );\n}\n"}]}
