﻿
/* ============================================================
   SOFIA KAMAL — Direction A · Locked design system
   ============================================================ */

const SK = {
  paper:       '#F2E8D5',
  paperDeep:   '#E8DCC2',
  ink:         '#3A2A1F',
  inkDeep:     '#2B1F1A',
  inkSoft:     '#5A4636',
  inkMute:     '#8A7560',
  border:      '#C9B79C',
  sienna:      '#6B4423',
  terracotta:  '#B5613B',
  ochre:       '#C9923D',
  mustard:     '#D4A847',
  dustyRose:   '#C97A6B',
  plum:        '#7A4A5C',
  sage:        '#8A9A6E',
  warmPeach:   '#E8B894',
  painting:    '#6B4423',
  ceramics:    '#B5613B',
  poetry:      '#7A4A5C',
  photography: '#2B1F1A',
  printmaking: '#E0A13A',
  display:     "'Fraunces', serif",
  body:        "'Inter', system-ui, sans-serif",
  bodySerif:   "'Fraunces', serif",
  mono:        "'JetBrains Mono', monospace",
  hand:        "'Caveat', cursive",
  ease:        'cubic-bezier(0.65, 0, 0.35, 1)',
};

function shade(hex, n) {
  const c = hex.replace('#','');
  const r = parseInt(c.substr(0,2),16), g = parseInt(c.substr(2,2),16), b = parseInt(c.substr(4,2),16);
  const f = 1 + n/100;
  const cl = (v) => Math.max(0, Math.min(255, Math.round(v*f)));
  return `#${cl(r).toString(16).padStart(2,'0')}${cl(g).toString(16).padStart(2,'0')}${cl(b).toString(16).padStart(2,'0')}`;
}
function hexToVec3(h) {
  const c = h.replace('#','');
  return [parseInt(c.substr(0,2),16)/255, parseInt(c.substr(2,2),16)/255, parseInt(c.substr(4,2),16)/255];
}

/* ---------- Paper grain + fiber overlays ---------- */
function PaperGrain({ opacity = 0.5, seed = 3 }) {
  return (
    <svg style={{position:'absolute',inset:0,width:'100%',height:'100%',pointerEvents:'none',mixBlendMode:'multiply',opacity}} aria-hidden>
      <filter id={`grain-${seed}`}>
        <feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed={seed} stitchTiles="stitch"/>
        <feColorMatrix values="0 0 0 0 0.23  0 0 0 0 0.16  0 0 0 0 0.12  0 0 0 0.18 0"/>
      </filter>
      <rect width="100%" height="100%" filter={`url(#grain-${seed})`}/>
    </svg>
  );
}
function PaperFiber({ opacity = 0.22, seed = 7 }) {
  return (
    <svg style={{position:'absolute',inset:0,width:'100%',height:'100%',pointerEvents:'none',mixBlendMode:'multiply',opacity}} aria-hidden>
      <filter id={`fiber-${seed}`}>
        <feTurbulence type="turbulence" baseFrequency="0.012 0.04" numOctaves="2" seed={seed}/>
        <feColorMatrix values="0 0 0 0 0.32  0 0 0 0 0.22  0 0 0 0 0.16  0 0 0 0.5 -0.3"/>
      </filter>
      <rect width="100%" height="100%" filter={`url(#fiber-${seed})`}/>
    </svg>
  );
}

/* ---------- WebGL watercolor wash ---------- */
function WebGLWatercolor({ colors, baseColor = SK.paper, intensity = 0.62, speed = 0.05 }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (typeof THREE === 'undefined') return;
    const el = ref.current; if (!el) return;
    const w = el.clientWidth, h = el.clientHeight;
    const dpr = Math.min(window.devicePixelRatio || 1, 1.5);

    const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: false });
    renderer.setPixelRatio(dpr);
    renderer.setSize(w, h);
    el.appendChild(renderer.domElement);
    Object.assign(renderer.domElement.style, { position:'absolute', inset:0, width:'100%', height:'100%', display:'block' });

    const scene = new THREE.Scene();
    const cam = new THREE.OrthographicCamera(-1,1,1,-1,0,1);

    const cols = colors.slice(0, 6).map(hexToVec3);
    while (cols.length < 6) cols.push(cols[cols.length - 1]);
    const base = hexToVec3(baseColor);

    const uniforms = {
      uTime:    { value: 0 },
      uRes:     { value: new THREE.Vector2(w, h) },
      uIntensity: { value: intensity },
      uBase:    { value: new THREE.Vector3(...base) },
      uC0: { value: new THREE.Vector3(...cols[0]) },
      uC1: { value: new THREE.Vector3(...cols[1]) },
      uC2: { value: new THREE.Vector3(...cols[2]) },
      uC3: { value: new THREE.Vector3(...cols[3]) },
      uC4: { value: new THREE.Vector3(...cols[4]) },
      uC5: { value: new THREE.Vector3(...cols[5]) },
    };

    const mat = new THREE.ShaderMaterial({
      uniforms,
      vertexShader: `varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position, 1.0);} `,
      fragmentShader: `
        precision highp float;
        varying vec2 vUv;
        uniform float uTime;
        uniform vec2  uRes;
        uniform float uIntensity;
        uniform vec3  uBase;
        uniform vec3  uC0,uC1,uC2,uC3,uC4,uC5;
        float hash(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
        float noise(vec2 p){
          vec2 i = floor(p), f = fract(p);
          float a = hash(i), b = hash(i+vec2(1.,0.)), c = hash(i+vec2(0.,1.)), d = hash(i+vec2(1.,1.));
          vec2 u = f*f*(3.-2.*f);
          return mix(a,b,u.x) + (c-a)*u.y*(1.-u.x) + (d-b)*u.x*u.y;
        }
        float fbm(vec2 p){
          float v = 0., a = 0.5;
          for (int i = 0; i < 5; i++){ v += a * noise(p); p *= 2.02; a *= 0.5; }
          return v;
        }
        void main(){
          vec2 uv = vUv;
          uv.x *= uRes.x / uRes.y;
          float t = uTime;
          vec2 q = vec2(fbm(uv * 1.4 + vec2(0.0, t*0.4)),
                        fbm(uv * 1.4 + vec2(5.2, t*0.3)));
          vec2 r = vec2(fbm(uv * 2.1 + 4.0*q + vec2(1.7, 9.2) + t*0.25),
                        fbm(uv * 2.1 + 4.0*q + vec2(8.3, 2.8) + t*0.22));
          float n  = fbm(uv * 1.6 + 4.0*r);
          float n2 = fbm(uv * 3.2 + 2.0*r + vec2(0., t*0.18));
          float n3 = fbm(uv * 0.8 + r * 1.3 + vec2(t*0.12, -t*0.1));
          float w0 = smoothstep(0.30, 0.95, n + 0.18*sin(t*0.11 + 1.0));
          float w1 = smoothstep(0.25, 0.85, n2 + 0.16*sin(t*0.09 + 2.3));
          float w2 = smoothstep(0.35, 0.90, fbm(uv*1.1 + r*2.0 + vec2(t*0.07, 0.)));
          float w3 = smoothstep(0.40, 0.95, n3 + 0.14*sin(t*0.13 + 4.1));
          float w4 = smoothstep(0.45, 0.92, fbm(uv*2.4 + q + vec2(0., t*0.08)));
          float w5 = smoothstep(0.30, 0.85, fbm(uv*0.6 + r*0.8 + t*0.04));
          vec3 col = uBase;
          col = mix(col, uC0, w0 * 0.55 * uIntensity);
          col = mix(col, uC1, w1 * 0.45 * uIntensity);
          col = mix(col, uC2, w2 * 0.38 * uIntensity);
          col = mix(col, uC3, w3 * 0.45 * uIntensity);
          col = mix(col, uC4, w4 * 0.35 * uIntensity);
          col = mix(col, uC5, w5 * 0.30 * uIntensity);
          float edge = abs(n - n2);
          col *= 1.0 - smoothstep(0.0, 0.08, edge) * 0.10;
          float g = (hash(gl_FragCoord.xy + t) - 0.5) * 0.025;
          col += g;
          float vig = smoothstep(1.4, 0.5, length(vUv - 0.5) * 1.6);
          col = mix(uBase, col, vig);
          gl_FragColor = vec4(col, 1.0);
        }
      `,
    });

    const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat);
    scene.add(quad);
    const start = performance.now();
    let raf;
    const tick = () => {
      uniforms.uTime.value = (performance.now() - start) * 0.001 * speed * 16;
      renderer.render(scene, cam);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    const ro = new ResizeObserver(() => {
      const W = el.clientWidth, H = el.clientHeight;
      renderer.setSize(W, H);
      uniforms.uRes.value.set(W, H);
    });
    ro.observe(el);
    return () => {
      cancelAnimationFrame(raf); ro.disconnect();
      renderer.dispose(); mat.dispose(); quad.geometry.dispose();
      if (renderer.domElement.parentNode) renderer.domElement.parentNode.removeChild(renderer.domElement);
    };
  }, [colors, baseColor, intensity, speed]);
  return <div ref={ref} style={{position:'absolute', inset:0, overflow:'hidden'}} aria-hidden/>;
}

/* ---------- View cursor (watercolor dot / brush-tip on links) ---------- */
function ViewCursor() {
  const [pos, setPos] = React.useState({x:-200,y:-200});
  const [hover, setHover] = React.useState(null);
  const [link, setLink] = React.useState(false);
  const [color, setColor] = React.useState(SK.sienna);
  const [trail, setTrail] = React.useState([]);
  const [impulses, setImpulses] = React.useState([]);
  const colorRef = React.useRef(SK.sienna);
  const pulseIdRef = React.useRef(0);
  const pulseTimeoutsRef = React.useRef([]);

  React.useEffect(() => {
    const m = (e) => {
      setPos({x:e.clientX, y:e.clientY});
      setTrail((t) => [...t.slice(-5), {x:e.clientX, y:e.clientY}]);
      const el = document.elementFromPoint(e.clientX, e.clientY);
      const tone = el && el.closest('[data-cursor-tone]');
      if (tone) {
        setColor(tone.dataset.cursorTone);
        colorRef.current = tone.dataset.cursorTone;
      }
      const view = el && el.closest('[data-cursor="view"]');
      setHover(view ? (view.dataset.cursorLabel || 'view') : null);
      const clickable = el && el.closest('a, button, [role="button"]');
      setLink(!!clickable && !view);
    };

    const onDown = (e) => {
      const target = e.target;
      if (!(target instanceof Element)) return;
      const clickable = target.closest('a, button, [role="button"]');
      if (!clickable) return;
      const tone = clickable.closest('[data-cursor-tone]');
      const pulseColor = tone?.dataset?.cursorTone || colorRef.current;
      const id = ++pulseIdRef.current;
      setImpulses((p) => [...p, { id, x: e.clientX, y: e.clientY, c: pulseColor }]);
      const t = setTimeout(() => {
        setImpulses((p) => p.filter((item) => item.id !== id));
      }, 520);
      pulseTimeoutsRef.current.push(t);
    };

    window.addEventListener('mousemove', m);
    window.addEventListener('pointerdown', onDown);
    return () => {
      window.removeEventListener('mousemove', m);
      window.removeEventListener('pointerdown', onDown);
      pulseTimeoutsRef.current.forEach(clearTimeout);
      pulseTimeoutsRef.current = [];
    };
  }, []);

  const big = !!hover;
  const isPhotographyTone = (color || '').toLowerCase() === SK.photography.toLowerCase();
  const dotColor = isPhotographyTone ? '#FFFFFF' : color;

  return (
    <>
      {impulses.map((p) => (
        <React.Fragment key={p.id}>
          <div style={{
            position:'fixed',
            left:p.x,
            top:p.y,
            width:16,
            height:16,
            borderRadius:'50%',
            border:`1.5px solid ${p.c}`,
            background:`${p.c}26`,
            transform:'translate(-50%,-50%)',
            pointerEvents:'none',
            zIndex:100001,
            animation:`skClickPulseRing 520ms ${SK.ease} forwards`,
          }}/>
          <div style={{
            position:'fixed',
            left:p.x,
            top:p.y,
            width:6,
            height:6,
            borderRadius:'50%',
            background:p.c,
            transform:'translate(-50%,-50%)',
            pointerEvents:'none',
            zIndex:100001,
            animation:`skClickPulseDot 420ms ${SK.ease} forwards`,
          }}/>
        </React.Fragment>
      ))}

      {/* trail only for default dot mode */}
      {!big && !link && trail.map((t, i) => (
        <div key={i} style={{
          position:'fixed',
          left:t.x,
          top:t.y,
          width:10-i,
          height:10-i,
          borderRadius:'50%',
          background: dotColor,
          opacity:(i+1)/16,
          mixBlendMode: isPhotographyTone ? 'normal' : 'multiply',
          filter: isPhotographyTone ? 'none' : 'blur(2px)',
          boxShadow: isPhotographyTone ? '0 0 0 0.9px #111111cc' : 'none',
          transform:'translate(-50%,-50%)',
          pointerEvents:'none',
          zIndex:99998,
        }}/>
      ))}

      {/* "view" big circle */}
      {big && (
        <div style={{
          position:'fixed', left: pos.x, top: pos.y,
          width: 72, height: 72, borderRadius:'50%',
          background: `${color}22`, border: `1px solid ${color}`,
          backdropFilter: 'blur(2px)',
          transform:'translate(-50%,-50%)', pointerEvents:'none', zIndex: 99999,
          transition: `background 400ms ${SK.ease}`,
          display:'flex', alignItems:'center', justifyContent:'center',
          fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.18em', textTransform:'uppercase',
          color: '#FFFFFF',
          textShadow: '0 1px 2px #00000066',
        }}>
          <span style={{
            display:'block',
            width:'100%',
            padding:'0 8px',
            textAlign:'center',
            lineHeight: 1.2,
            whiteSpace:'pre-line',
            wordBreak:'break-word',
          }}>
            {hover}
          </span>
        </div>
      )}

      {/* link calligraphy tip */}
      {!big && link && (
        <div style={{
          position:'fixed',
          left: pos.x,
          top: pos.y - 25,
          width: 26,
          height: 26,
          background: color,
          WebkitMaskImage: "url('assets/calligraphy-tip.png')",
          maskImage: "url('assets/calligraphy-tip.png')",
          WebkitMaskSize: '100% 100%',
          maskSize: '100% 100%',
          WebkitMaskRepeat: 'no-repeat',
          maskRepeat: 'no-repeat',
          WebkitMaskPosition: 'left top',
          maskPosition: 'left top',
          pointerEvents:'none',
          zIndex: 99999,
          transition: `opacity 200ms ${SK.ease}`,
        }}/>
      )}

      {/* default dot */}
      {!big && !link && (
        <div style={{
          position:'fixed', left: pos.x, top: pos.y,
          width: 14, height: 14, borderRadius:'50%',
          background: dotColor,
          border: isPhotographyTone ? '1.7px solid #111111' : 'none',
          boxSizing:'border-box',
          mixBlendMode: isPhotographyTone ? 'normal' : 'multiply',
          transform:'translate(-50%,-50%)', pointerEvents:'none', zIndex: 99999,
        }}/>
      )}

      <style>{`
        @keyframes skClickPulseRing {
          0%   { transform: translate(-50%,-50%) scale(0.3); opacity: 0.95; }
          70%  { opacity: 0.45; }
          100% { transform: translate(-50%,-50%) scale(2.4); opacity: 0; }
        }
        @keyframes skClickPulseDot {
          0%   { transform: translate(-50%,-50%) scale(1); opacity: 0.92; }
          100% { transform: translate(-50%,-50%) scale(0.4); opacity: 0; }
        }
      `}</style>
    </>
  );
}

/* ---------- SVG fallback wash (used on inner pages) ---------- */
function WatercolorWash({ blobs = [], opacity = 0.32, displaceId = 'wc' }) {
  return (
    <div style={{position:'absolute',inset:0,overflow:'hidden',pointerEvents:'none'}}>
      <svg style={{position:'absolute',inset:0,width:'100%',height:'100%'}} aria-hidden>
        <defs>
          <filter id={`${displaceId}-disp`} x="-20%" y="-20%" width="140%" height="140%">
            <feTurbulence type="fractalNoise" baseFrequency="0.012" numOctaves="2" seed="4"/>
            <feDisplacementMap in="SourceGraphic" scale="38"/>
            <feGaussianBlur stdDeviation="6"/>
          </filter>
        </defs>
        <g filter={`url(#${displaceId}-disp)`} opacity={opacity}>
          {blobs.map((b, i) => (
            <circle key={i} cx={`${b.x}%`} cy={`${b.y}%`} r={b.r} fill={b.color}
              style={{
                mixBlendMode: 'multiply',
                animation: `wcfloat-${displaceId}-${i} ${b.drift || 22}s ${SK.ease} ${b.delay || 0}s infinite alternate`,
              }}/>
          ))}
        </g>
      </svg>
      <style>{blobs.map((b, i) => `
        @keyframes wcfloat-${displaceId}-${i} {
          0%   { transform: translate(0,0) scale(1) rotate(0deg); }
          50%  { transform: translate(${b.dx || 18}px, ${b.dy || -12}px) scale(${b.s || 1.08}) rotate(${b.dr || 6}deg); }
          100% { transform: translate(${b.dx2 || -10}px, ${b.dy2 || 14}px) scale(${b.s2 || 0.96}) rotate(${b.dr2 || -4}deg); }
        }
      `).join('')}</style>
    </div>
  );
}

/* ---------- Painted-edge image placeholder ---------- */
function PaintedFrame({ color = SK.sienna, label = '', subLabel = '', aspect = '4 / 5', stripes = true, accent = null, seed = 1, height = null }) {
  const s = seed * 7 + 3;
  return (
    <div style={{
      position:'relative', width:'100%',
      aspectRatio: aspect || undefined,
      height: aspect ? undefined : (height || '100%'),
      overflow:'hidden', background: color,
    }}>
      <div style={{position:'absolute',inset:0,background:`linear-gradient(${135 + seed*23}deg, ${color} 0%, ${shade(color, -8)} 60%, ${shade(color, 8)} 100%)`}}/>
      {stripes && (
        <svg style={{position:'absolute',inset:0,width:'100%',height:'100%',opacity:0.18}} aria-hidden>
          <defs>
            <pattern id={`stripes-${s}`} width="10" height="10" patternUnits="userSpaceOnUse" patternTransform={`rotate(${seed*15+30})`}>
              <line x1="0" y1="0" x2="0" y2="10" stroke="#fff" strokeWidth="1.2"/>
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill={`url(#stripes-${s})`}/>
        </svg>
      )}
      {accent && (
        <svg style={{position:'absolute',inset:0,width:'100%',height:'100%'}} aria-hidden>
          <filter id={`splotch-${s}`}>
            <feTurbulence type="fractalNoise" baseFrequency="0.015" numOctaves="2" seed={s}/>
            <feDisplacementMap in="SourceGraphic" scale="22"/>
          </filter>
          <g filter={`url(#splotch-${s})`} style={{mixBlendMode:'multiply', opacity: 0.7}}>
            <ellipse cx={`${30 + (seed%3)*20}%`} cy={`${40 + (seed%2)*20}%`} rx="35%" ry="28%" fill={accent}/>
          </g>
        </svg>
      )}
      <PaperGrain opacity={0.35} seed={s}/>
      {(label || subLabel) && (
        <div style={{position:'absolute',left:12,bottom:12,fontFamily:SK.mono, fontSize:10, lineHeight:1.4, color:SK.paper, letterSpacing:'0.06em', textTransform:'uppercase', opacity:0.92}}>
          <div>{label}</div>
          {subLabel && <div style={{opacity:0.7}}>{subLabel}</div>}
        </div>
      )}
    </div>
  );
}

function BrushDivider({ color = SK.ink, height = 6, seed = 1 }) {
  return (
    <svg width="100%" height={height} viewBox={`0 0 200 ${height}`} preserveAspectRatio="none" style={{display:'block'}}>
      <defs>
        <filter id={`brushd-${seed}`}>
          <feTurbulence type="fractalNoise" baseFrequency="0.9 0.4" numOctaves="2" seed={seed}/>
          <feDisplacementMap in="SourceGraphic" scale="2.5"/>
        </filter>
      </defs>
      <rect x="0" y={height*0.3} width="200" height={height*0.4} fill={color} filter={`url(#brushd-${seed})`} opacity="0.85"/>
    </svg>
  );
}

/* ============================================================
   NAVIGATION
   ============================================================ */
function FooterBar({ left, right, accent = SK.sienna }) {
  return (
    <div style={{
      position:'absolute', bottom: 24, left: 'clamp(20px, 4vw, 56px)', right: 'clamp(20px, 4vw, 56px)', zIndex: 10,
      display:'flex', justifyContent:'space-between', alignItems:'center',
      fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.2em',
      textTransform:'uppercase', color: SK.inkMute,
    }}>
      <span style={{display:'flex',alignItems:'center',gap:10}}>{left}</span>
      <span style={{display:'flex',alignItems:'center',gap:10}}>
        <span style={{display:'inline-block',width:7,height:7,borderRadius:'50%',background:accent,animation:`pulseSK 3s ${SK.ease} infinite`}}/>
        {right}
      </span>
    </div>
  );
}

/* ============================================================
   HERO  (locked spec)
   ============================================================ */
function Hero({ go, setActiveMedium }) {
  const p = SK;
  const mediums = [
    {label:'Painter',      id:'painting',    color: SK.painting},
    {label:'Ceramicist',   id:'ceramics',    color: SK.ceramics},
    {label:'Poet',         id:'poetry',      color: SK.poetry},
    {label:'Printmaker',   id:'printmaking', color: SK.printmaking},
    {label:'Photographer', id:'photography', color: SK.photography},
  ];
  const [mIdx, setMIdx] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setMIdx(i => (i+1) % mediums.length), 2600);
    return () => clearInterval(id);
  }, []);

  // Sliding underline indicator
  const itemRefs = React.useRef([]);
  const [indicator, setIndicator] = React.useState({left: 0, width: 0, top: 0});
  React.useLayoutEffect(() => {
    const el = itemRefs.current[mIdx];
    if (el) setIndicator({left: el.offsetLeft, width: el.offsetWidth, top: el.offsetTop + el.offsetHeight - 2});
  }, [mIdx]);
  const activeColor = mediums[mIdx].color;

  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => { const t = setTimeout(() => setMounted(true), 80); return () => clearTimeout(t); }, []);

  const rev = (i) => ({
    opacity: mounted ? 1 : 0,
    transform: mounted ? 'translateY(0)' : 'translateY(20px)',
    transition: `opacity 1200ms ${SK.ease} ${i*80}ms, transform 1200ms ${SK.ease} ${i*80}ms`,
  });

  const heroBlobs = [
    { color: SK.painting,    x: 24, y: 24, r: 188, drift: 24, dx: 16,  dy: -18, s: 1.06, dx2: -10, dy2: -8 },
    { color: SK.ceramics,    x: 78, y: 64, r: 170, drift: 30, dx: -14, dy: 12,  s: 1.04, dx2: 10,  dy2: -10, delay: 2 },
    { color: SK.photography, x: 58, y: 17, r: 118, drift: 22, dx: 10,  dy: 4,   s: 0.95, dx2: -12, dy2: -8, delay: 4 },
  ];

  return (
    <div style={{
      position:'relative', width:'100%', minHeight:'100vh',
      background: p.paper, color: p.ink, fontFamily: p.body, overflow:'hidden',
    }} data-cursor-tone={p.sienna}>

      <WatercolorWash blobs={heroBlobs} opacity={0.5} displaceId="hero"/>
      <div style={{position:'absolute',inset:0,background:'transparent',pointerEvents:'none'}}/>
      <PaperGrain opacity={0.55} seed={3}/>
      <PaperFiber opacity={0.3} seed={7}/>
      <div style={{
        position:'absolute',
        left:0,
        right:0,
        bottom:0,
        height:'clamp(120px, 18vh, 240px)',
        background:`linear-gradient(180deg, ${p.paper}00 0%, ${p.paper}c9 38%, ${p.paper} 68%, ${p.paper} 100%)`,
        pointerEvents:'none',
        zIndex: 4,
      }}/>

      <div className="hero-two-zone" style={{
        position:'relative', zIndex: 5,
        display:'grid', gridTemplateColumns:'55fr 45fr', alignItems:'center',
        padding:'140px clamp(20px, 4vw, 56px) 100px', gap: 'clamp(32px, 4vw, 56px)',
        minHeight:'100vh', boxSizing:'border-box',
      }}>
        {/* LEFT */}
        <div>
          <h1 className="hero-name" style={{
            ...rev(1),
            fontFamily: p.display,
            fontWeight: 350,
            fontSize: 'clamp(64px, 9.5vw, 160px)',
            lineHeight: 0.92,
            letterSpacing:'-0.025em',
            margin:'0 0 28px',
            color: p.ink,
            fontVariationSettings:'"opsz" 144, "SOFT" 30',
          }}>
            Sofia<br/>
            <span style={{
              fontStyle:'italic', fontWeight: 300, color: p.sienna,
              fontVariationSettings:'"opsz" 144, "SOFT" 50',
            }}>Kamal</span>
          </h1>

          <div style={{
            ...rev(2),
            position:'relative',
            display:'flex', alignItems:'baseline', gap: 14, flexWrap:'wrap',
            fontFamily: p.bodySerif, fontSize: 'clamp(18px, 1.6vw, 22px)', lineHeight: 1.4,
            color: p.inkSoft, marginBottom: 18,
          }}>
            {/* sliding underline — color tracks the active medium */}
            <span aria-hidden style={{
              position:'absolute',
              left: indicator.left, top: indicator.top,
              width: indicator.width, height: 6,
              background: `${activeColor}cc`,
              zIndex: 0, pointerEvents:'none',
              transition: `left 700ms ${SK.ease}, width 700ms ${SK.ease}, top 700ms ${SK.ease}, background 700ms ${SK.ease}`,
            }}/>
            {mediums.map((m, i) => {
              const active = i === mIdx;
              return (
                <React.Fragment key={m.id}>
                  <button
                    ref={el => { itemRefs.current[i] = el; }}
                    onClick={() => { setActiveMedium(m.id); go('works', m.id); }}
                    data-cursor-tone={m.color}
                    style={{
                      position:'relative', zIndex: 1,
                      background:'transparent', border:'none', padding: 0,
                      fontFamily: p.bodySerif, fontSize: 'inherit', lineHeight: 1.4,
                      fontStyle: active ? 'italic' : 'normal',
                      color: active ? m.color : p.inkMute,
                      fontWeight: active ? 500 : 400,
                      transition: `color 700ms ${SK.ease}, font-weight 700ms ${SK.ease}`,
                      cursor:'none',
                    }}
                  >
                    {m.label}
                  </button>
                  {i < mediums.length - 1 && <span style={{color: p.border, fontSize: 14, position:'relative', zIndex: 1}}>·</span>}
                </React.Fragment>
              );
            })}
          </div>

          <p style={{
            ...rev(3),
            fontFamily: p.bodySerif, fontStyle:'italic', fontWeight: 300,
            fontSize: 'clamp(18px, 1.7vw, 24px)', lineHeight: 1.45,
            color: p.inkSoft, margin:'0 0 48px', maxWidth: 520,
          }}>
            Undergraduate student at Stanford University.
          </p>

          <div className="link-row" style={{
            ...rev(4),
            display:'flex', gap: 0, alignItems:'stretch', flexWrap:'wrap',
            paddingTop: 24, borderTop: `1px solid ${p.border}`, maxWidth: 480,
          }}>
            {[
              {l:'Email',  href:'mailto:sofiakamal06@gmail.com', sub:'sofiakamal06@gmail.com'},
              {l:'Resume', href:'assets/resume.pdf', sub:'PDF · download', download: true},
            ].map((link, i, arr) => (
              <a key={link.l}
                href={link.href}
                target={link.download ? '_blank' : (link.href.startsWith('http') ? '_blank' : undefined)}
                rel={link.download || link.href.startsWith('http') ? 'noreferrer' : undefined}
                download={link.download ? '' : undefined}
                onClick={(e) => { if (link.onClick) { e.preventDefault(); link.onClick(); } }}
                data-cursor-tone={p.sienna}
                style={{
                  flex: 1, minWidth: 130, textDecoration:'none', color: p.ink,
                  padding: '18px 18px 0 0',
                  borderRight: i < arr.length - 1 ? `1px solid ${p.border}` : 'none',
                  marginRight: i < arr.length - 1 ? 18 : 0,
                  display:'block',
                }}>
                <div style={{
                  fontFamily: p.body, fontSize: 13, fontWeight: 500,
                  letterSpacing:'0.08em', textTransform:'uppercase',
                  color: p.ink, marginBottom: 6,
                  display:'flex', alignItems:'center', gap: 6,
                }}>
                  {link.l}
                  <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M2 8L8 2M8 2H3M8 2V7" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>
                </div>
                <div style={{fontFamily: p.mono, fontSize: 10, letterSpacing:'0.06em', color: p.inkMute}}>
                  {link.sub}
                </div>
              </a>
            ))}
          </div>
        </div>

        {/* CENTER — scroll hint */}
        <div className="hero-scroll-hint" style={{
          ...rev(5),
          position:'absolute', left: '54%', top: '50%',
          transform:'translate(-50%, -50%)',
          zIndex: 6, pointerEvents:'none',
          textAlign:'center',
        }}>
          <div className="scroll-float" style={{
            display:'flex', flexDirection:'column', alignItems:'center', gap: 12,
          }}>
            <div style={{
              fontFamily: p.hand, fontSize: 30, color: p.sienna,
              transform:'rotate(-3deg)', lineHeight: 1,
            }}>
              Scroll down for works…
            </div>
            <svg width="120" height="170" viewBox="0 0 120 170" fill="none" style={{overflow:'visible'}}>
              {/* looped calligraphic down-arrow */}
              <path
                d="M 72 14
                   C 56 30, 52 52, 64 66
                   C 74 78, 88 68, 88 52
                   C 88 38, 78 34, 70 44
                   C 58 58, 60 76, 70 84
                   C 84 96, 104 92, 108 76
                   C 112 62, 100 56, 90 66
                   C 78 80, 80 102, 80 142"
                stroke={p.sienna}
                strokeWidth="3.1"
                strokeLinecap="round"
                strokeLinejoin="round"
                fill="none"
              />
              <path
                d="M 67 136 L 80 160 L 93 136 L 80 146 Z"
                fill={p.sienna}
              />
            </svg>
          </div>
        </div>

        {/* RIGHT — tilted portrait + vessel + quote card */}
        <div className="hero-portrait-wrap" style={{
          ...rev(3),
          position:'relative', height:'100%', minHeight: 600,
        }}>
          {/* Main tilted portrait */}
          <div data-cursor="view" data-cursor-label={"Paint-\ning"} className="hero-portrait-main" style={{
            position:'absolute', right: 30, top: 20, width: 360, height: 460,
            transform: 'rotate(2deg)',
            boxShadow: `0 18px 40px -12px ${p.ink}55, 0 0 0 12px ${p.paper}, 0 0 0 13px ${p.paperDeep}`,
            overflow:'hidden',
          }}>
            <img
              src="assets/works/home-main-painting.jpg"
              alt="Painting by Sofia Kamal"
              loading="eager"
              style={{
                width:'100%',
                height:'100%',
                objectFit:'cover',
                display:'block',
              }}
            />
          </div>

          {/* Small vessel card */}
          <div data-cursor="view" data-cursor-label={"Cera-\nmics"} data-cursor-tone={p.ceramics} className="hero-vessel" style={{
            position:'absolute', right: 280, top: 360, width: 130, height: 130,
            transform: 'rotate(-6deg)',
            boxShadow: `0 12px 28px -8px ${p.ink}55, 0 0 0 8px ${p.paper}`,
            zIndex: 2,
          }}>
            <img
              src="assets/works/main-ceramics-3.jpg"
              alt="Ceramic work"
              loading="eager"
              style={{
                width:'100%',
                height:'100%',
                objectFit:'cover',
                display:'block',
              }}
            />
          </div>

          {/* Quote card — pinned as a sticker note below the portrait */}
          <div className="hero-quote-card" style={{
            position:'absolute', right: 30, top: 462, width: 200,
            background: p.paper, padding:'14px 16px',
            transform:'rotate(5deg)',
            boxShadow:`0 8px 22px -6px ${p.ink}66`,
            fontFamily: p.bodySerif, fontStyle:'italic',
            fontSize: 14, lineHeight: 1.5, color: p.inkSoft, zIndex: 3,
          }}>
            <div style={{position:'absolute',top:-8,left:'50%',width:14,height:14,borderRadius:'50%',background:p.poetry,transform:'translateX(-50%)',boxShadow:`0 2px 4px ${p.ink}55`}}/>
            <div>“It was a<br/>dream of nightjars and a grove of sequoia trees”</div>
            <div style={{fontFamily:p.mono, fontStyle:'normal', fontSize:9, letterSpacing:'0.1em', textTransform:'uppercase', color:p.inkMute, marginTop:8}}>
              — Homecoming, Augury
            </div>
          </div>
        </div>
      </div>

      <div style={{
        position:'absolute', bottom: 24, left: 'clamp(20px, 4vw, 56px)', zIndex: 10,
        fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.2em',
        textTransform:'uppercase', color: SK.inkMute,
        display:'flex', alignItems:'center', gap: 10,
      }}>
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M5 1V9M5 9L1 5M5 9L9 5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>
        scroll · works
      </div>

      <style>{`
        @keyframes pulseSK { 0%,100% { opacity: 1 } 50% { opacity: 0.35 } }
        @keyframes scrollFloat {
          0%, 100% { transform: translateY(-6px); }
          50%      { transform: translateY(8px); }
        }
        .scroll-float { animation: scrollFloat 4.2s ease-in-out infinite; }
        @media (max-width: 900px) {
          .hero-two-zone { grid-template-columns: 1fr !important; padding-top: 110px !important; }
          .hero-portrait-wrap { order: -1; margin-bottom: 24px; min-height: 540px !important; }
          .hero-portrait-main { width: 70% !important; height: 360px !important; right: 12% !important; top: 0 !important; }
          .hero-vessel { right: 6% !important; top: 280px !important; bottom: auto !important; width: 100px !important; height: 100px !important; }
          .hero-quote-card { right: 18% !important; top: 380px !important; bottom: auto !important; width: 180px !important; }
          .hero-scroll-hint { display: none !important; }
          .link-row > a { flex: 1 1 45% !important; min-width: 0 !important; }
          .sk-nav { gap: 14px !important; font-size: 10px !important; }
        }
      `}</style>
    </div>
  );
}

function TornPortrait() {
  const p = SK;
  return (
    <div data-cursor="view" data-cursor-label="portrait" style={{
      position:'relative', width: '88%', maxWidth: 460, aspectRatio: '4/5',
    }}>
      <svg width="0" height="0" style={{position:'absolute'}}>
        <defs>
          <filter id="torn-edge" x="-5%" y="-5%" width="110%" height="110%">
            <feTurbulence type="fractalNoise" baseFrequency="0.012" numOctaves="3" seed="7" result="noise"/>
            <feDisplacementMap in="SourceGraphic" in2="noise" scale="14"/>
          </filter>
          <filter id="torn-edge-strong" x="-8%" y="-8%" width="116%" height="116%">
            <feTurbulence type="fractalNoise" baseFrequency="0.018" numOctaves="3" seed="13" result="noise"/>
            <feDisplacementMap in="SourceGraphic" in2="noise" scale="22"/>
          </filter>
        </defs>
      </svg>
      <div style={{
        position:'absolute', inset:'-3% -3% -2% -3%',
        background: p.paperDeep,
        filter: 'url(#torn-edge-strong)',
        boxShadow: `0 30px 60px -20px ${p.inkDeep}55, 0 12px 24px -8px ${p.inkDeep}33`,
      }}/>
      <div style={{
        position:'absolute', inset:'-1.5%',
        background: p.paper,
        filter: 'url(#torn-edge)',
      }}>
        <PaperGrain opacity={0.5} seed={5}/>
      </div>
      <div style={{
        position:'absolute', inset: 0,
        filter: 'url(#torn-edge)',
        overflow:'hidden',
      }}>
        <PortraitImage/>
        <PaperGrain opacity={0.35} seed={9}/>
        <div style={{position:'absolute',inset:0,background:`linear-gradient(160deg, ${p.warmPeach}22, transparent 40%, ${p.sienna}11)`}}/>
      </div>
      <div style={{
        position:'absolute', top:-14, left:'12%', width: 78, height: 22,
        background:`${p.warmPeach}aa`, transform:'rotate(-6deg)',
        boxShadow:`0 2px 6px ${p.inkDeep}22`,
        clipPath:'polygon(2% 20%, 98% 8%, 100% 80%, 4% 92%)',
      }}/>
      <div style={{
        position:'absolute', bottom:-12, right:'18%', width: 90, height: 22,
        background:`${p.ochre}99`, transform:'rotate(4deg)',
        boxShadow:`0 2px 6px ${p.inkDeep}22`,
        clipPath:'polygon(0% 12%, 96% 22%, 100% 86%, 6% 96%)',
      }}/>
    </div>
  );
}

function PortraitImage() {
  const p = SK;
  return (
    <div style={{position:'absolute', inset: 0, overflow:'hidden'}}>
      <div style={{
        position:'absolute', inset: 0,
        background: `linear-gradient(165deg, ${shade(p.warmPeach, -8)} 0%, ${shade(p.terracotta, 8)} 40%, ${p.sienna} 75%, ${p.inkDeep} 100%)`,
      }}/>
      <svg viewBox="0 0 300 380" preserveAspectRatio="xMidYMid slice" style={{position:'absolute',inset:0,width:'100%',height:'100%'}}>
        <defs>
          <filter id="port-blur"><feGaussianBlur stdDeviation="3"/></filter>
          <filter id="port-disp">
            <feTurbulence type="fractalNoise" baseFrequency="0.018" numOctaves="3" seed="3"/>
            <feDisplacementMap in="SourceGraphic" scale="10"/>
          </filter>
        </defs>
        <g filter="url(#port-disp)" opacity="0.85">
          <ellipse cx="60" cy="80" rx="120" ry="90" fill={p.warmPeach}/>
          <ellipse cx="240" cy="60" rx="80" ry="70" fill={p.ochre}/>
          <ellipse cx="280" cy="180" rx="100" ry="70" fill={p.dustyRose} opacity="0.85"/>
          <ellipse cx="20" cy="220" rx="80" ry="100" fill={p.sage} opacity="0.7"/>
        </g>
        <g filter="url(#port-disp)">
          <ellipse cx="150" cy="135" rx="58" ry="72" fill={shade(p.terracotta, -5)} opacity="0.9"/>
          <path d="M 92 105 Q 100 65 150 60 Q 205 65 215 115 Q 215 145 200 150 Q 175 95 150 95 Q 125 95 100 145 Q 88 130 92 105 Z" fill={p.inkDeep} opacity="0.85"/>
          <path d="M 50 380 Q 60 240 150 220 Q 245 240 260 380 Z" fill={shade(p.sienna, -10)}/>
          <path d="M 100 380 Q 120 280 150 270 Q 180 280 205 380 Z" fill={p.terracotta} opacity="0.6"/>
          <ellipse cx="150" cy="200" rx="40" ry="14" fill={p.inkDeep} opacity="0.4"/>
        </g>
        <g opacity="0.7">
          <ellipse cx="135" cy="120" rx="6" ry="3" fill={p.inkDeep}/>
          <ellipse cx="170" cy="120" rx="6" ry="3" fill={p.inkDeep}/>
          <path d="M 138 165 Q 150 175 162 165" stroke={p.inkDeep} strokeWidth="2" fill="none" opacity="0.7" strokeLinecap="round"/>
        </g>
        <ellipse cx="220" cy="160" rx="120" ry="180" fill={p.warmPeach} opacity="0.18" filter="url(#port-blur)"/>
      </svg>
    </div>
  );
}

/* ============================================================
   WORKS GALLERIES (all mediums)
   ============================================================ */
const MEDIA = [
  {id:'painting',    n:'Painting',     c: SK.painting,    short:'paint'},
  {id:'ceramics',    n:'Ceramics',     c: SK.ceramics,    short:'cera'},
  {id:'poetry',      n:'Poetry',       c: SK.poetry,      short:'poet'},
  {id:'printmaking', n:'Prints', c: SK.printmaking, short:'print'},
  {id:'photography', n:'Photography',  c: SK.photography, short:'photo'},
];

const WORKS_META = {
  painting: {
    title: 'Painting',
    accent: SK.painting,
    stat: '8 works - oil and charcoal',
  },
  ceramics: {
    title: 'Ceramics',
    accent: SK.ceramics,
    stat: '6 works - ceramic forms and vessels',
  },
  poetry: {
    title: 'Poetry',
    accent: SK.poetry,
    stat: '2 published poems',
  },
  photography: {
    title: 'Photography',
    accent: SK.photography,
    stat: '9 photographs - 35mm and medium format film',
  },
  printmaking: {
    title: 'Prints',
    accent: SK.printmaking,
    stat: '1 print',
  },
};

const PAINTING_WORKS = [
  { id:'p-01', title:'Painting 1', year:'[]', medium:'Oil paint', dimensions:'[]', image:'assets/works/painting-1.jpg', color:SK.painting, accent:SK.ceramics, seed:2, aspect:'1030 / 1280', displayMaxHeight:'min(700px, 76vh)', displayMaxWidth:'min(500px, 88vw)' },
  { id:'p-02', title:'Painting 2', year:'[]', medium:'Oil paint', dimensions:'[]', image:'assets/works/painting-2.jpg', color:shade(SK.ceramics, -8), accent:SK.photography, seed:5, aspect:'1007 / 1280', displayMaxHeight:'min(700px, 76vh)', displayMaxWidth:'min(500px, 88vw)' },
  { id:'p-03', title:'Painting 3', year:'[]', medium:'Oil paint', dimensions:'[]', image:'assets/works/painting-3.jpg', color:shade(SK.painting, 8), accent:SK.poetry, seed:8, aspect:'960 / 1280', displayMaxHeight:'min(700px, 76vh)', displayMaxWidth:'min(500px, 88vw)' },
  { id:'p-04', title:'Painting 4', year:'[]', medium:'Oil paint', dimensions:'[]', image:'assets/works/painting-4.jpg', color:shade(SK.poetry, 12), accent:SK.painting, seed:11, aspect:'989 / 1280', displayMaxHeight:'min(700px, 76vh)', displayMaxWidth:'min(500px, 88vw)' },
  { id:'p-05', title:'Painting 5', year:'[]', medium:'Oil paint', dimensions:'[]', image:'assets/works/painting-5.jpg', color:SK.photography, accent:SK.painting, seed:14, aspect:'1280 / 931', displayMaxHeight:'min(650px, 70vh)', displayMaxWidth:'min(680px, 92vw)' },
  { id:'p-06', title:'Painting 6', year:'[]', medium:'Oil paint', dimensions:'[]', image:'assets/works/painting-6.jpg', color:shade(SK.painting, -8), accent:SK.warmPeach, seed:17, aspect:'1000 / 1280', displayMaxHeight:'min(700px, 76vh)', displayMaxWidth:'min(500px, 88vw)' },
  { id:'p-07', title:'Painting 7', year:'[]', medium:'Charcoal drawing', dimensions:'[]', image:'assets/works/painting-7.jpg', color:SK.inkDeep, accent:SK.inkSoft, seed:20, aspect:'1280 / 1025', displayMaxHeight:'min(650px, 70vh)', displayMaxWidth:'min(650px, 92vw)' },
  { id:'p-08', title:'Painting 8', year:'[]', medium:'Charcoal drawing', dimensions:'[]', image:'assets/works/painting-8.jpg', color:SK.inkDeep, accent:SK.inkSoft, seed:23, aspect:'963 / 1280', displayMaxHeight:'min(700px, 76vh)', displayMaxWidth:'min(500px, 88vw)' },
];

const CERAMICS_WORKS = [
  { id:'c-01', title:'Ceramics 1', year:'[]', medium:'Ceramics', dimensions:'[]', image:'assets/works/ceramics-1.jpg', color:shade(SK.ceramics, -6), accent:SK.warmPeach, seed:3, aspect:'960 / 1280' },
  { id:'c-02', title:'Ceramics 2', year:'[]', medium:'Ceramics', dimensions:'[]', image:'assets/works/ceramics-2.jpg', color:shade(SK.warmPeach, -14), accent:SK.ceramics, seed:6, aspect:'960 / 1280' },
  { id:'c-03', title:'Ceramics 3', year:'[]', medium:'Ceramics', dimensions:'[]', image:'assets/works/ceramics-3.jpg', color:shade(SK.ceramics, 8), accent:SK.sienna, seed:9, aspect:'960 / 1280' },
  { id:'c-04', title:'Ceramics 4', year:'[]', medium:'Ceramics', dimensions:'[]', image:'assets/works/ceramics-4.jpg', color:shade(SK.terracotta, -5), accent:SK.poetry, seed:12, aspect:'1280 / 960' },
  { id:'c-05', title:'Ceramics 5', year:'[]', medium:'Ceramics', dimensions:'[]', image:'assets/works/ceramics-5.jpg', color:shade(SK.ochre, -18), accent:SK.ceramics, seed:15, aspect:'960 / 1280' },
  { id:'c-06', title:'Ceramics 6', year:'[]', medium:'Ceramics', dimensions:'[]', image:'assets/works/ceramics-6.jpg', color:shade(SK.ceramics, -12), accent:SK.painting, seed:18, aspect:'1280 / 960' },
];

const POETRY_SOURCES = [
  {
    id: 'academy-poets',
    name: 'Academy of American Poets poets.org',
    href: 'https://poets.org/poet/sofia-kamal',
    poems: [
      {
        id: 'po-01',
        title: 'Homecoming, augury',
        year: '2024',
        stanzas: [
          ['I have lived around the corner from the houses of jinn,', 'held collapsed stars in my hands like I could reopen them.'],
          ['Outside, the street is littered with acorns and the bodies', 'of dead parables—tell me, do you know where to lay a hurricane'],
          ['to rest? The old women who interpreted', 'nightmares and the migration patterns of birds'],
          ['died last Thursday in her sleep—collect azaleas, minor', 'keys, other debris of this life. All things return home—'],
          ['pollen born of dahlias and the last syllable', 'on your tongue, a night sky with exit wounds.'],
          ['The whispers of wind chimes cling to the morning', 'and the bronze I broke off the edge of the sun. In the garden,'],
          ['the honeyed insides of figs are sunk into earth', 'to wash over all the death held in this soil.'],
          ['Look, I couldn’t tell you what the blue jays', 'grieve, only that they live, so they must'],
          ['mourn. And I recognize in fire its hunger', 'or love, maybe I felt that once'],
          ['in a dream I don’t remember now. It was a', 'dream of nightjars and a grove of sequoia trees'],
          ['and other omens of danger. I wake to the sea,', 'brimming with salt and sleep, mottles the shore.'],
          ['The sound has slept long years inside the mouths', 'of bells, and I want to coax it out, the way blood longs'],
          ['to leave these veins or these scraps of language settle in dense air.', 'No one sees the bullets streak the sky softly in the dusk,'],
          ['and every unanswered prayer, splintered on broken clouds,', 'returns to these hands I hold out for your name.'],
        ],
      },
    ],
  },
  {
    id: 'national-student-poets',
    name: '2024 National Student Poets Program Chapbook',
    href: 'https://www.imls.gov/our-work/partnerships/national-student-poets-program',
    poems: [
      {
        id: 'po-02',
        title: 'Gas station',
        year: '2024',
        align: 'center',
        variant: 'chapbook',
        showYear: false,
        stanzas: [
          ['Defamiliarize yourself', 'with the tongues and light', 'you hold in your mouth'],
          ['if you want to know why', 'the blood is red. Tonight', 'the moon is lobed with'],
          ['desire left unanswered,', 'its edge rusted over', 'by centuries of eyes'],
          ['that seek its face—think,', [{ text:'the casualties,', italic:true }, ' exploit.'], 'We stopped'],
          ['to fill his car with gas', 'out of habit, not to come', 'or leave. We are always left'],
          ['defiled without direction—', [{ text:'hittites,', italic:true }, ' a man drags'], 'a cigarette from his lips,'],
          ['his back against the wall', 'of a drugstore like he holds', 'the weight of the city'],
          ['and its molted wings. Look,', 'a stitch of stars to sew the rips', 'in the sky. In the street, oil pooling,'],
          ['I found the wings of a monarch,', 'glazed with petrol at my feet,', 'black and orange and flight'],
          ['seeping from the tips. You know,', 'colors fracture like bones', 'in my hand. The fibers'],
          ['of a tumbleweed unravel', 'like any civilization. I watch', 'from the hood of the car,'],
          ['wrap the skyline and', 'these borders around', 'my fingertips in the night.'],
          ['The violence of a cityscape.', 'The gasoline I sink into.', 'When nations are cut, they'],
          ['bleed. Know', 'it’s not blood,', [{ text:'it’s oil.', italic:true }]],
          ['Like all fables this ends without meaning.'],
        ],
      },
    ],
  },
];

const PHOTOGRAPHY_WORKS = [
  { id:'ph-01', title:'Photo 1', year:'2026', medium:'35mm film', dimensions:'16 x 20 in print', note:'Kodak Portra 400, natural light only.', image:'assets/works/photo-1.jpg', color:shade(SK.photography, -6), accent:SK.warmPeach, seed:4, aspect:'3/4' },
  { id:'ph-02', title:'Photo 2', year:'2026', medium:'35mm film', dimensions:'12 x 18 in print', note:'Shot handheld at 1/30 to hold low light grain.', image:'assets/works/photo-2.jpg', color:shade(SK.painting, -14), accent:SK.photography, seed:7, aspect:'3/4' },
  { id:'ph-03', title:'Photo 3', year:'2025', medium:'Medium format', dimensions:'20 x 20 in print', note:'Waist-level portrait study in the shared studio kitchen.', image:'assets/works/photo-3.jpg', color:shade(SK.warmPeach, -12), accent:SK.sienna, seed:10, aspect:'3/4' },
  { id:'ph-04', title:'Photo 4', year:'2025', medium:'35mm film', dimensions:'11 x 14 in print', note:'Color charting by observation instead of notes.', image:'assets/works/photo-4.jpg', color:shade(SK.ochre, -16), accent:SK.photography, seed:13, aspect:'3/4' },
  { id:'ph-05', title:'Photo 5', year:'2025', medium:'35mm film', dimensions:'16 x 20 in print', note:'Close crop from a contact sheet of twelve frames.', image:'assets/works/photo-5.jpg', color:shade(SK.ceramics, -22), accent:SK.ceramics, seed:16, aspect:'3/4' },
  { id:'ph-06', title:'Photo 6', year:'2024', medium:'35mm film', dimensions:'12 x 18 in print', note:'Soft overexposure kept to preserve afternoon glow.', image:'assets/works/photo-6.jpg', color:shade(SK.warmPeach, -6), accent:SK.painting, seed:19, aspect:'3/4' },
  { id:'ph-07', title:'Photo 7', year:'2024', medium:'35mm film', dimensions:'11 x 14 in print', note:'Shot two hours after unloading the kiln.', image:'assets/works/photo-7.jpg', color:shade(SK.photography, 8), accent:SK.terracotta, seed:22, aspect:'3/4' },
  { id:'ph-08', title:'Photo 8', year:'2024', medium:'35mm film', dimensions:'11 x 14 in print', note:'Documenting painting setup before a final critique.', image:'assets/works/photo-8.jpg', color:shade(SK.printmaking, 18), accent:SK.photography, seed:25, aspect:'3/4' },
  { id:'ph-09', title:'Photo 9', year:'2023', medium:'35mm film', dimensions:'12 x 18 in print', note:'Long exposure from the back seat, no tripod.', image:'assets/works/photo-9.jpg', color:shade(SK.poetry, -8), accent:SK.photography, seed:28, aspect:'3/4' },
];

const PRINT_WORKS = [
  { id:'pr-01', title:'Print 1', year:'[]', medium:'Print', dimensions:'[]', image:'assets/works/print-1.jpg', color:SK.inkDeep, accent:SK.printmaking, seed:5, aspect:'752 / 1280', displayMaxHeight:'min(700px, 76vh)', displayMaxWidth:'min(470px, 88vw)' },
];

function MediumSwitcher({ active, setActive }) {
  return (
    <div style={{padding:'8px clamp(20px, 4vw, 56px) 28px', position:'relative', zIndex: 10}}>
      <div style={{
        fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.18em',
        textTransform:'uppercase', color: SK.inkMute, marginBottom: 12,
      }}>
        Works / Medium switcher
      </div>
      <div className="ms-rail" style={{
        display:'flex', gap: 0, alignItems:'baseline', flexWrap:'wrap',
        borderTop:`1px solid ${SK.ink}33`, borderBottom:`1px solid ${SK.ink}33`, padding:'14px 0',
      }}>
        {MEDIA.map((m, i) => {
          const isActive = active === m.id;
          return (
            <button key={m.id}
              onClick={() => setActive(m.id)}
              data-cursor-tone={m.c}
              style={{
                background:'transparent', border:'none', padding: 0,
                display:'flex', alignItems:'baseline', gap: 12,
                paddingRight: 24, marginRight: 24,
                borderRight: i < MEDIA.length - 1 ? `1px solid ${SK.ink}22` : 'none',
                cursor:'none', fontFamily: 'inherit',
              }}>
              <span style={{fontFamily: SK.mono, fontSize: 11, color: SK.inkMute}}>0{i+1}</span>
              <span style={{
                fontFamily: SK.display,
                fontStyle: isActive ? 'italic' : 'normal',
                fontSize: 'clamp(20px, 2vw, 28px)',
                fontWeight: 400,
                color: isActive ? m.c : SK.inkSoft,
                opacity: isActive ? 1 : 0.58,
                position:'relative',
                transition: `color 600ms ${SK.ease}, opacity 600ms ${SK.ease}`,
              }}>
                {m.n}
                {isActive && (
                  <svg width="100%" height="12" viewBox="0 0 120 12" preserveAspectRatio="none"
                    style={{position:'absolute', left:0, right:0, bottom:-8, overflow:'visible'}}>
                    <path d="M2 8 C 18 2, 42 11, 64 7 C 78 5, 96 10, 118 6"
                      stroke={m.c} strokeWidth="2.6" strokeLinecap="round" fill="none" opacity="0.95"/>
                  </svg>
                )}
              </span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function LazyArtwork({ children, minHeight = 260, align = 'stretch' }) {
  const ref = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver((entries) => {
      if (entries[0] && entries[0].isIntersecting) {
        setVisible(true);
        obs.disconnect();
      }
    }, { rootMargin: '220px 0px' });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  return (
    <div ref={ref} style={{
      minHeight,
      width:'100%',
      display:'flex',
      justifyContent: align,
    }}>
      {visible ? children : (
        <div style={{
          height: minHeight,
          width:'100%',
          maxWidth: 360,
          background: `linear-gradient(145deg, ${SK.paperDeep}, ${shade(SK.paperDeep, 8)})`,
          border: `1px dashed ${SK.border}`,
        }}/>
      )}
    </div>
  );
}

function WorksAmbient({ medium, embedded = false }) {
  if (medium === 'painting') {
    return (
      <>
        <WatercolorWash
          blobs={[
            { color: SK.painting, x: 84, y: 16, r: 170, drift: 30, dx: -12, dy: 16 },
            { color: SK.terracotta, x: 12, y: 86, r: 180, drift: 32, dx: 14, dy: -8, delay: 2 },
            { color: SK.warmPeach, x: 44, y: 22, r: 120, drift: 28, dx: 10, dy: 8, delay: 4 },
          ]}
          opacity={0.32}
          displaceId="works-paint"
        />
        <PaperGrain opacity={0.5} seed={3}/>
        {embedded && <PaperFiber opacity={0.24} seed={7}/>}
      </>
    );
  }

  if (medium === 'ceramics') {
    return (
      <>
        <WatercolorWash
          blobs={[
            { color: SK.terracotta, x: 18, y: 18, r: 130, drift: 34, dx: 8, dy: 6 },
            { color: SK.ceramics, x: 92, y: 72, r: 180, drift: 36, dx: -12, dy: 14, delay: 2 },
          ]}
          opacity={0.22}
          displaceId="works-cera"
        />
        <div className="ceramic-ambient-wrap" aria-hidden>
          <div className="ceramic-ambient-core"/>
          <div className="ceramic-ambient-ring"/>
        </div>
        <PaperGrain opacity={0.52} seed={8}/>
      </>
    );
  }

  if (medium === 'poetry') {
    return (
      <>
        <WatercolorWash
          blobs={[
            { color: SK.poetry, x: 90, y: 12, r: 120, drift: 30, dx: -10, dy: 10 },
            { color: shade(SK.poetry, 22), x: 14, y: 84, r: 140, drift: 30, dx: 8, dy: -8, delay: 2 },
          ]}
          opacity={0.2}
          displaceId="works-poetry"
        />
        <svg
          className="poetry-ambient-ink"
          viewBox="0 0 1000 120"
          preserveAspectRatio="none"
          aria-hidden
          style={{
            position: embedded ? 'absolute' : 'fixed',
            left: 0,
            right: 0,
            bottom: 0,
            width: '100%',
            height: embedded ? 120 : 140,
            pointerEvents:'none',
            opacity: embedded ? 0.26 : 0.36,
            zIndex: 1,
          }}
        >
          <path
            className="poetry-ambient-path"
            d="M 0 90 C 120 72, 190 104, 300 84 C 410 64, 510 108, 620 80 C 720 56, 850 100, 1000 74"
            fill="none"
            stroke={SK.poetry}
            strokeWidth="3"
            strokeLinecap="round"
          />
        </svg>
        <PaperGrain opacity={0.54} seed={12}/>
      </>
    );
  }

  if (medium === 'printmaking') {
    return (
      <>
        <div style={{
          position:'absolute',
          inset:0,
          background: `radial-gradient(circle at 10% 20%, ${SK.warmPeach}33 0%, transparent 38%), radial-gradient(circle at 86% 74%, ${SK.printmaking}22 0%, transparent 42%)`,
          pointerEvents:'none',
        }}/>
        <PaperGrain opacity={0.64} seed={16}/>
      </>
    );
  }

  if (medium === 'photography') {
    return (
      <>
        <WatercolorWash
          blobs={[
            { color: shade(SK.photography, 30), x: 16, y: 16, r: 100, drift: 24, dx: 8, dy: 8 },
            { color: shade(SK.inkDeep, 20), x: 90, y: 78, r: 140, drift: 26, dx: -10, dy: -8, delay: 2 },
          ]}
          opacity={0.18}
          displaceId="works-photo"
        />
        <div className="print-ink-spread" aria-hidden>
          <span/>
          <span/>
          <span/>
        </div>
        <PaperGrain opacity={0.58} seed={20}/>
      </>
    );
  }

  return null;
}

function WorksHeader({ medium }) {
  const meta = WORKS_META[medium];
  return (
    <div className="works-header" style={{
      padding:'28px clamp(20px, 4vw, 56px) 44px',
      display:'grid', gridTemplateColumns:'1fr', gap: 48, alignItems:'end',
      position:'relative', zIndex: 5,
    }}>
      <div>
        <h1 style={{
          fontFamily: SK.display, fontWeight: 400,
          fontSize: 'clamp(56px, 9vw, 122px)', lineHeight: 0.92,
          letterSpacing:'-0.02em', margin: 0, color: meta.accent,
        }}>
          <span style={{fontStyle:'italic'}}>{meta.title}</span>
        </h1>
        <div style={{
          fontFamily: SK.mono, fontSize: 11, letterSpacing:'0.18em',
          textTransform:'uppercase', color: SK.inkMute, marginTop: 18,
        }}>
          {meta.stat}
        </div>
      </div>
    </div>
  );
}

function ArtworkFrame({ work, aspect, stripes = true, label = '', subLabel = '', shadow, maxHeight = null, maxWidth = null }) {
  const frameStyle = work.image
    ? {filter:`drop-shadow(0 18px 28px ${SK.ink}33)`, width:'100%', maxWidth:maxWidth || undefined}
    : {boxShadow: shadow || `0 18px 42px -16px ${SK.ink}66`};
  if (work.image) {
    return (
      <div style={frameStyle}>
        <div style={{
          position:'relative',
          width:'100%',
          aspectRatio: aspect || work.aspect || '4 / 5',
          overflow:'hidden',
          background: 'transparent',
          maxHeight: maxHeight || undefined,
          margin:'0 auto',
        }}>
          <img
            src={work.image}
            alt={work.title}
            loading="lazy"
            style={{
              position:'absolute',
              inset:0,
              width:'100%',
              height:'100%',
              objectFit:'contain',
              display:'block',
              background: 'transparent',
            }}
          />
        </div>
      </div>
    );
  }

  return (
    <div style={frameStyle}>
      <PaintedFrame
        color={work.color}
        accent={work.accent}
        aspect={aspect}
        label={label}
        subLabel={subLabel}
        seed={work.seed}
        stripes={stripes}
      />
    </div>
  );
}

function WorkImageButton({ work, onOpen, aspect = '4/5', shadow, stripes = true, label = 'view', lazy = false, minHeight = 280, align = 'flex-start' }) {
  const frame = <ArtworkFrame work={work} aspect={aspect} shadow={shadow} stripes={stripes} maxHeight={work.displayMaxHeight} maxWidth={work.displayMaxWidth}/>;

  return (
    <button
      onClick={() => onOpen(work)}
      data-cursor="view"
      data-cursor-label={label}
      data-cursor-tone={work.accent || work.color}
      style={{
        background:'transparent',
        border:'none',
        padding:0,
        width:'100%',
        textAlign:'left',
        cursor:'none',
        display:'flex',
        justifyContent: align,
      }}
      aria-label={`Open ${work.title} details`}
    >
      {lazy ? <LazyArtwork minHeight={minHeight} align={align}>{frame}</LazyArtwork> : frame}
    </button>
  );
}

function PaintingSection({ onOpen }) {
  const works = PAINTING_WORKS;
  return (
    <section style={{position:'relative', zIndex: 5}}>
      <div style={{padding:'0 clamp(20px, 4vw, 56px) 88px'}}>
        {works.map((work, idx) => {
          const number = idx + 1;
          const imageOnRight = idx % 2 === 0;
          return (
            <article key={work.id} className="painting-alt-row" style={{
              display:'grid',
              gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)',
              gap: 'clamp(22px, 3vw, 44px)',
              alignItems:'start',
              marginTop: idx === 0 ? 0 : 58,
            }}>
              <div style={{
                order: imageOnRight ? 2 : 1,
                justifySelf: imageOnRight ? 'start' : 'end',
                width:'100%',
                display:'flex',
                justifyContent: imageOnRight ? 'flex-start' : 'flex-end',
              }}>
                <WorkImageButton
                  work={work}
                  onOpen={onOpen}
                  aspect={work.aspect}
                  label={`view no.${String(number).padStart(2, '0')}`}
                  lazy={idx > 0}
                  minHeight={(work.aspect || '').startsWith('1280') ? 280 : 380}
                  align={imageOnRight ? 'flex-start' : 'flex-end'}
                />
              </div>
              <div style={{
                order: imageOnRight ? 1 : 2,
                justifySelf: imageOnRight ? 'end' : 'start',
                width:'min(330px, 100%)',
                textAlign: imageOnRight ? 'right' : 'left',
              }}>
                <div style={{fontFamily: SK.display, fontStyle:'italic', fontSize:'clamp(28px, 3.2vw, 44px)', lineHeight:1.02, color: SK.ink}}>
                  {work.title}
                </div>
                <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.16em', textTransform:'uppercase', color: SK.inkMute, marginTop: 10}}>
                  no.{String(number).padStart(2, '0')} - {work.year} - {work.medium}
                </div>
                <div style={{marginTop:18, paddingTop:14, borderTop:`1px solid ${SK.ink}22`, fontFamily: SK.body, fontSize: 12, color: SK.inkMute, lineHeight: 1.7}}>
                  <strong style={{color: SK.ink, fontWeight:500}}>Click image</strong> - Opens full details
                </div>
              </div>
            </article>
          );
        })}
      </div>
    </section>
  );
}

function CeramicsSection({ onOpen }) {
  return (
    <section style={{padding:'0 clamp(20px, 4vw, 56px) 96px', position:'relative', zIndex: 5}}>
      <div className="ceramics-grid" style={{
        columnCount: 3,
        columnGap: 'clamp(18px, 2.4vw, 30px)',
      }}>
        {CERAMICS_WORKS.map((work, idx) => {
          return (
            <figure key={work.id} style={{
              margin: 0,
              display:'inline-block',
              width:'100%',
              breakInside:'avoid',
              marginBottom:'clamp(24px, 3vw, 38px)',
            }}>
              <figcaption style={{
                marginBottom: 10,
                paddingBottom: 10,
                borderBottom:`1px solid ${SK.ink}22`,
              }}>
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', gap: 14}}>
                  <span style={{fontFamily: SK.display, fontStyle:'italic', fontSize:'clamp(20px, 2vw, 28px)', color: SK.ink, lineHeight: 1.05}}>
                    {work.title}
                  </span>
                  <span style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.14em', textTransform:'uppercase', color: SK.inkMute, whiteSpace:'nowrap'}}>
                    {work.year}
                  </span>
                </div>
                <div style={{marginTop:7, fontFamily: SK.mono, fontSize: 9, letterSpacing:'0.14em', textTransform:'uppercase', color: SK.inkMute}}>
                  Click image - Opens full details
                </div>
              </figcaption>
              <button
                onClick={() => onOpen(work)}
                data-cursor="view"
                data-cursor-label={`view ${idx + 1}`}
                data-cursor-tone={SK.ceramics}
                style={{
                  width:'100%',
                  background:'transparent',
                  border:'none',
                  padding:0,
                  cursor:'none',
                  textAlign:'left',
                }}
                aria-label={`Open ${work.title} details`}
              >
                <LazyArtwork minHeight={idx === 0 ? 300 : 230} align="center">
                  <div style={{
                    width:'100%',
                    aspectRatio: work.aspect,
                    maxWidth: (work.aspect || '').startsWith('1280') ? 'min(520px, 100%)' : 'min(390px, 100%)',
                    margin:'0 auto',
                    boxShadow:`0 20px 46px -22px ${SK.ink}66`,
                    overflow:'hidden',
                    background: SK.paperDeep,
                  }}>
                    {work.image ? (
                      <img
                        src={work.image}
                        alt={work.title}
                        loading="lazy"
                        style={{
                          width:'100%',
                          height:'100%',
                          objectFit:'cover',
                          display:'block',
                        }}
                      />
                    ) : (
                      <PaintedFrame
                        color={work.color}
                        accent={work.accent}
                        aspect={null}
                        height="100%"
                        label={work.title.toUpperCase()}
                        subLabel={work.medium.toUpperCase()}
                        seed={work.seed}
                      />
                    )}
                  </div>
                </LazyArtwork>
              </button>
            </figure>
          );
        })}
      </div>
    </section>
  );
}

function PoetrySection() {
  const renderPoemLine = (line) => {
    if (!Array.isArray(line)) return line;
    return line.map((part, i) => (
      typeof part === 'string'
        ? <React.Fragment key={i}>{part}</React.Fragment>
        : <em key={i} style={{fontStyle:'italic'}}>{part.text}</em>
    ));
  };
  const getPoemLineText = (line) => {
    if (!Array.isArray(line)) return line;
    return line.map(part => typeof part === 'string' ? part : part.text).join('');
  };
  const getChapbookIndent = (line) => {
    const measure = 38;
    const length = getPoemLineText(line).length;
    return Math.max(0, (measure - length) / 2);
  };

  return (
    <section style={{padding:'0 clamp(20px, 4vw, 56px) 96px', position:'relative', zIndex: 5}}>
      <div className="poetry-column" style={{maxWidth: 1040, margin:'0 auto'}}>
        {POETRY_SOURCES.map((source, sourceIdx) => (
          <section key={source.id} style={{
            padding:'44px 0 42px',
            borderTop: sourceIdx === 0 ? `2px solid ${SK.poetry}` : `1px solid ${SK.ink}26`,
          }}>
            <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.18em', textTransform:'uppercase', color: SK.inkMute, marginBottom: 12}}>
              Source
            </div>
            <a
              href={source.href}
              target="_blank"
              rel="noreferrer"
              data-cursor-tone={SK.poetry}
              style={{
                fontFamily: SK.display,
                fontStyle:'italic',
                fontSize:'clamp(26px, 3.4vw, 44px)',
                lineHeight:1.05,
                color: SK.poetry,
                textDecorationLine:'underline',
                textDecorationColor: SK.poetry,
                textDecorationThickness:'1px',
                textUnderlineOffset:'0.16em',
              }}
            >
              {source.name}
            </a>

            {source.poems.map((poem, poemIdx) => {
              const isChapbook = poem.variant === 'chapbook';
              return (
              <article key={poem.id} className={`poem-page${isChapbook ? ' chapbook-poem-page' : ''}`} style={{
                padding: poemIdx === 0 ? '42px 0 8px' : '54px 0 8px',
                maxWidth: 'none',
                margin: 0,
                animation:`poemLift 1200ms ${SK.ease} both`,
                animationDelay:`${(sourceIdx + poemIdx) * 80}ms`,
              }}>
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', gap: 16, flexWrap:'wrap'}}>
                  <h2 style={{
                    margin:0,
                    fontFamily: SK.display,
                    fontWeight: 400,
                    fontStyle: 'italic',
                    fontSize: 'clamp(40px, 6vw, 72px)',
                    lineHeight: 0.96,
                    color: SK.ink,
                  }}>
                    {poem.title}
                  </h2>
                  {poem.showYear !== false && (
                    <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.16em', textTransform:'uppercase', color: SK.inkMute}}>
                      {poem.year}
                    </div>
                  )}
                </div>

                <div className={`poem-body${isChapbook ? ' chapbook-poem-body' : ''}`} style={{
                  margin: '30px 0 0',
                  maxWidth: isChapbook ? 720 : 'none',
                  textAlign: 'left',
                }}>
                  {poem.stanzas.map((stanza, stanzaIdx) => (
                    <p key={stanzaIdx} style={{
                      margin: '0 0 22px',
                      fontFamily: SK.bodySerif,
                      fontStyle: 'italic',
                      fontSize: 'clamp(18px, 1.7vw, 25px)',
                      lineHeight: 1.48,
                      color: stanzaIdx === 0 ? SK.ink : SK.inkSoft,
                    }}>
                      {stanza.map((line, lineIdx) => (
                        <span
                          key={lineIdx}
                          className={`poem-line${isChapbook ? ' chapbook-poem-line' : ''}`}
                          style={{
                            display:'block',
                            '--line-indent': isChapbook ? `${getChapbookIndent(line)}ch` : '0ch',
                          }}
                        >
                          {renderPoemLine(line)}
                        </span>
                      ))}
                    </p>
                  ))}
                </div>
              </article>
            )})}
          </section>
        ))}
      </div>
      <style>{`
        .poem-line {
          white-space: nowrap;
        }
        .chapbook-poem-line {
          padding-left: var(--line-indent);
        }
        @media (max-width: 680px) {
          .poem-body {
            overflow: visible !important;
          }
          .poem-line {
            white-space: normal;
            overflow-wrap: normal;
            word-break: normal;
          }
          .chapbook-poem-line {
            padding-left: min(var(--line-indent), 18vw);
          }
        }
      `}</style>
    </section>
  );
}

function GridGallerySection({ onOpen, works, tone }) {
  return (
    <section style={{padding:'0 clamp(20px, 4vw, 56px) 96px', position:'relative', zIndex: 5}}>
      <div className="photo-grid" style={{display:'grid', gridTemplateColumns:'repeat(3, minmax(0, 1fr))', gap: 10}}>
        {works.map((work, idx) => (
          <figure key={work.id} style={{margin:0}}>
            <button
              onClick={() => onOpen(work)}
              data-cursor="view"
              data-cursor-label={`view ${idx + 1}`}
              data-cursor-tone={tone}
              style={{background:'transparent', border:'none', padding:0, width:'100%', cursor:'none', textAlign:'left'}}
              aria-label={`Open ${work.title} details`}
            >
              <LazyArtwork minHeight={230}>
                <div style={{boxShadow:`0 14px 30px -16px ${SK.ink}66`}}>
                  <PaintedFrame
                    color={work.color}
                    accent={work.accent}
                    aspect={work.aspect}
                    label=""
                    subLabel=""
                    seed={work.seed}
                    stripes={false}
                  />
                </div>
              </LazyArtwork>
            </button>
            <figcaption style={{marginTop: 8, fontFamily: SK.mono, fontSize: 9, letterSpacing:'0.15em', textTransform:'uppercase', color: SK.inkMute}}>
              {work.title} - {work.year}
            </figcaption>
          </figure>
        ))}
      </div>
    </section>
  );
}

function PrintsSection({ onOpen }) {
  const work = PRINT_WORKS[0];
  return (
    <section style={{position:'relative', zIndex: 5}}>
      <div style={{
        padding:'0 clamp(20px, 4vw, 56px) 96px',
        display:'grid',
        justifyItems:'center',
      }}>
        <article style={{width:'min(520px, 100%)'}}>
          <div style={{
            marginBottom: 18,
            paddingBottom: 14,
            borderBottom:`1px solid ${SK.ink}22`,
          }}>
            <div style={{fontFamily: SK.display, fontStyle:'italic', fontSize:'clamp(28px, 3.2vw, 44px)', lineHeight:1.02, color: SK.ink}}>
              {work.title}
            </div>
            <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.16em', textTransform:'uppercase', color: SK.inkMute, marginTop: 10}}>
              no.01 - {work.year} - {work.medium}
            </div>
            <div style={{marginTop:18, paddingTop:14, borderTop:`1px solid ${SK.ink}22`, fontFamily: SK.body, fontSize: 12, color: SK.inkMute, lineHeight: 1.7}}>
              <strong style={{color: SK.ink, fontWeight:500}}>Click image</strong> - Opens full details
            </div>
          </div>

          <WorkImageButton
            work={work}
            onOpen={onOpen}
            aspect={work.aspect}
            label="view no.01"
            align="center"
          />
        </article>

        <div style={{
          marginTop: 54,
          fontFamily: SK.bodySerif,
          fontStyle:'italic',
          fontSize:'clamp(24px, 3vw, 38px)',
          color: SK.inkSoft,
          textAlign:'center',
        }}>
          More coming soon...
        </div>
      </div>
    </section>
  );
}

function PrintmakingSection({
  onOpen,
  works = PRINT_WORKS,
  tone = SK.photography,
  featuredLabel = 'Featured work',
}) {
  const featured = works[0];
  const rest = works.slice(1);
  const renderMattedWork = (work, options = {}) => (
    <div style={{background: SK.paperDeep, padding: options.outerPadding || 10, boxShadow: options.shadow || 'none'}}>
      <div style={{border:`1px solid ${SK.border}`, padding: options.innerPadding || 7}}>
        {work.image ? (
          <div style={{
            position:'relative',
            width:'100%',
            aspectRatio: work.aspect || '3/4',
            overflow:'hidden',
            background: SK.paper,
          }}>
            <img
              src={work.image}
              alt={work.title}
              loading={options.eager ? 'eager' : 'lazy'}
              style={{
                position:'absolute',
                inset:0,
                width:'100%',
                height:'100%',
                objectFit:'cover',
                display:'block',
              }}
            />
          </div>
        ) : (
          <PaintedFrame
            color={work.color}
            accent={work.accent}
            aspect={work.aspect}
            label={work.title.toUpperCase()}
            subLabel={(work.dimensions || work.medium || '').toUpperCase()}
            seed={work.seed}
            stripes={false}
          />
        )}
      </div>
    </div>
  );

  return (
    <section style={{padding:'0 clamp(20px, 4vw, 56px) 96px', position:'relative', zIndex: 5}}>
      <div style={{background: shade(tone, 8), border:`1px solid ${shade(tone, 24)}88`, padding: '24px clamp(14px, 2vw, 28px) 26px'}}>
        <div className="print-hero" style={{display:'grid', gridTemplateColumns:'1.6fr 1fr', gap: 24, alignItems:'start'}}>
          <figure style={{margin:0}}>
            <button
              onClick={() => onOpen(featured)}
              data-cursor="view"
              data-cursor-label="view hero"
              data-cursor-tone={tone}
              style={{background:'transparent', border:'none', padding:0, width:'100%', cursor:'none', textAlign:'left'}}
              aria-label={`Open ${featured.title} details`}
            >
              {renderMattedWork(featured, { outerPadding: 12, innerPadding: 8, shadow: `0 20px 46px -20px #000000`, eager: true })}
            </button>
          </figure>

          <aside style={{paddingTop: 4}}>
            <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.18em', textTransform:'uppercase', color: shade(SK.paper, -4), marginBottom: 12}}>
              {featuredLabel}
            </div>
            <div style={{fontFamily: SK.display, fontStyle:'italic', fontSize:'clamp(28px, 3.2vw, 46px)', lineHeight:1.02, color: SK.paper}}>
              {featured.title}
            </div>
            <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.14em', textTransform:'uppercase', color: shade(SK.paperDeep, -8), marginTop: 10}}>
              {featured.year} - {featured.medium}
            </div>
          </aside>
        </div>

        <div className="print-grid" style={{display:'grid', gridTemplateColumns:'repeat(3, minmax(0, 1fr))', gap: 18, marginTop: 24}}>
          {rest.map((work, idx) => (
            <figure key={work.id} style={{margin:0}}>
              <button
                onClick={() => onOpen(work)}
                data-cursor="view"
                data-cursor-label={`view ${idx + 2}`}
                data-cursor-tone={tone}
                style={{background:'transparent', border:'none', padding:0, width:'100%', cursor:'none', textAlign:'left'}}
                aria-label={`Open ${work.title} details`}
              >
                {renderMattedWork(work)}
              </button>
              <figcaption style={{marginTop: 8, fontFamily: SK.mono, fontSize: 9, letterSpacing:'0.15em', textTransform:'uppercase', color: shade(SK.paperDeep, -14)}}>
                {work.title} - {work.year}
              </figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

function WorksLightbox({ item, onClose }) {
  React.useEffect(() => {
    if (!item) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [item, onClose]);

  if (!item) return null;

  return (
    <div
      onClick={onClose}
      style={{
        position:'fixed', inset:0, zIndex: 12000,
        background: `${SK.inkDeep}cc`,
        backdropFilter:'blur(8px)',
        padding:'clamp(20px, 3vw, 36px)',
        display:'flex', alignItems:'center', justifyContent:'center',
      }}
      role="dialog"
      aria-modal="true"
      aria-label={`${item.title} details`}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width:'min(1100px, 100%)',
          maxHeight:'92vh',
          overflow:'auto',
          background: SK.paper,
          border:`1px solid ${SK.border}`,
          boxShadow:`0 24px 80px -32px #000`,
          position:'relative',
        }}
      >
        <button
          onClick={onClose}
          aria-label="Close lightbox"
          style={{
            position:'absolute', top:12, right:12, zIndex:2,
            width:32, height:32, borderRadius:'50%',
            border:`1px solid ${SK.ink}44`, background:SK.paper,
            color:SK.ink, fontFamily:SK.mono, fontSize:11, cursor:'none',
          }}
        >
          x
        </button>

        <div className="lightbox-grid" style={{display:'grid', gridTemplateColumns:'1.3fr 1fr', gap: 24, padding: 24}}>
          <div>
            <ArtworkFrame
              work={{...item, seed:(item.seed || 1) + 40}}
              aspect={item.aspect || '4/5'}
              label={item.title.toUpperCase()}
              subLabel={(item.medium || '').toUpperCase()}
              stripes={item.medium && item.medium.toLowerCase().includes('film') ? false : true}
            />
          </div>
          <div>
            <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.16em', textTransform:'uppercase', color: SK.inkMute, marginBottom: 10}}>
              Work details
            </div>
            <h3 style={{margin:'0 0 12px', fontFamily: SK.display, fontWeight: 400, fontStyle:'italic', fontSize:'clamp(32px, 5vw, 52px)', lineHeight:0.96, color: item.accent || SK.sienna}}>
              {item.title}
            </h3>
            <div style={{display:'grid', gap: 8, fontFamily: SK.body, fontSize: 14, color: SK.inkSoft, lineHeight: 1.6}}>
              <div><strong style={{fontWeight:500, color:SK.ink}}>Year:</strong> {item.year || 'N/A'}</div>
              <div><strong style={{fontWeight:500, color:SK.ink}}>Medium:</strong> {item.medium || item.form || 'N/A'}</div>
              <div><strong style={{fontWeight:500, color:SK.ink}}>Dimensions:</strong> {item.dimensions || 'Variable'}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function WorksFooter({ activeMedium, setActiveMedium, go }) {
  const idx = MEDIA.findIndex(m => m.id === activeMedium);
  const next = MEDIA[(idx + 1) % MEDIA.length];
  const poetryCount = POETRY_SOURCES.reduce((total, source) => total + source.poems.length, 0);
  const selectedCount = ({
    painting: PAINTING_WORKS.length,
    ceramics: CERAMICS_WORKS.length,
    poetry: poetryCount,
    photography: PHOTOGRAPHY_WORKS.length,
    printmaking: PRINT_WORKS.length,
  })[activeMedium];
  const footerLabel = activeMedium === 'poetry'
    ? `Showing ${selectedCount} published poems`
    : `Showing ${selectedCount} selected ${selectedCount === 1 ? 'piece' : 'pieces'} - click any image for details`;

  return (
    <div style={{
      padding:'40px clamp(20px, 4vw, 56px) 60px',
      borderTop:`1px solid ${SK.ink}22`,
      display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap: 16,
      position:'relative', zIndex: 5,
    }}>
      <div style={{fontFamily: SK.mono, fontSize: 11, letterSpacing:'0.16em', textTransform:'uppercase', color: SK.inkMute}}>
        {footerLabel}
      </div>
      <div style={{display:'flex', gap: 18, alignItems:'center', fontFamily: SK.body, fontSize: 13}}>
        <a href="#" onClick={(e) => { e.preventDefault(); go('about'); }} style={{color: SK.inkMute, textDecoration:'none'}}>
          About Sofia
        </a>
        <span style={{color: SK.inkMute}}>Next medium -</span>
        <a href="#" onClick={(e) => { e.preventDefault(); setActiveMedium(next.id); }} style={{
          fontFamily: SK.display, fontStyle:'italic', fontSize: 24, color: next.c, textDecoration:'none',
        }}>
          {next.n}
        </a>
      </div>
    </div>
  );
}

function HomeWorksAll({ go }) {
  const [lightboxItem, setLightboxItem] = React.useState(null);
  const order = ['painting', 'ceramics', 'poetry', 'printmaking', 'photography'];

  const renderMedium = (medium) => {
    if (medium === 'painting') return <PaintingSection onOpen={setLightboxItem}/>;
    if (medium === 'ceramics') return <CeramicsSection onOpen={setLightboxItem}/>;
    if (medium === 'poetry') return <PoetrySection/>;
    if (medium === 'printmaking') return <PrintsSection onOpen={setLightboxItem}/>;
    if (medium === 'photography') return <PrintmakingSection onOpen={setLightboxItem} works={PHOTOGRAPHY_WORKS} tone={SK.photography} featuredLabel="Featured photograph"/>;
    return null;
  };

  return (
    <div style={{
      position:'relative',
      width:'100%',
      minHeight:'100vh',
      background: SK.paper,
      color: SK.ink,
      fontFamily: SK.body,
      overflow:'hidden',
    }} data-cursor-tone={SK.sienna}>
      {order.map((medium, idx) => (
        <section
          key={medium}
          data-cursor-tone={WORKS_META[medium].accent}
          style={{
            position:'relative',
            overflow:'hidden',
            borderTop: idx === 0 ? 'none' : `1px solid ${SK.ink}22`,
          }}
        >
          <WorksAmbient medium={medium} embedded/>
          {idx === 0 && (
            <div
              aria-hidden
              style={{
                position:'absolute',
                left:0,
                right:0,
                top:0,
                height:'clamp(180px, 24vh, 320px)',
                pointerEvents:'none',
                zIndex: 3,
                background:`linear-gradient(180deg, ${SK.paper} 0%, ${SK.paper} 36%, ${SK.paper}dd 62%, ${SK.paper}00 100%)`,
              }}
            />
          )}
          <div style={{position:'relative', zIndex:5}}>
            <WorksHeader medium={medium}/>
            {renderMedium(medium)}
          </div>
        </section>
      ))}

      <div style={{
        padding:'40px clamp(20px, 4vw, 56px) 62px',
        borderTop:`1px solid ${SK.ink}22`,
        display:'flex',
        justifyContent:'space-between',
        alignItems:'center',
        flexWrap:'wrap',
        gap: 16,
      }}>
        <a href="#" onClick={(e) => { e.preventDefault(); go('works'); }} style={{
          fontFamily: SK.display,
          fontStyle:'italic',
          fontSize: 26,
          color: SK.painting,
          textDecoration:'none',
        }}>
          Works page
        </a>
        <a href="#" onClick={(e) => { e.preventDefault(); go('about'); }} style={{
          fontFamily: SK.mono,
          fontSize: 11,
          letterSpacing:'0.16em',
          textTransform:'uppercase',
          color: SK.inkMute,
          textDecoration:'none',
        }}>
          Continue to About →
        </a>
      </div>

      <WorksLightbox item={lightboxItem} onClose={() => setLightboxItem(null)}/>

      <style>{`
        @keyframes ceramicTurn {
          0% { transform: rotate(0deg) scale(1); }
          50% { transform: rotate(180deg) scale(1.05); }
          100% { transform: rotate(360deg) scale(1); }
        }
        @keyframes poetryTrace {
          0% { stroke-dashoffset: 1400; opacity: 0.35; }
          30% { opacity: 0.65; }
          60% { opacity: 0.55; }
          100% { stroke-dashoffset: 0; opacity: 0.32; }
        }
        @keyframes printSpread {
          0% { transform: scale(0.35); opacity: 0; filter: blur(20px); }
          55% { opacity: 0.24; filter: blur(14px); }
          100% { transform: scale(1); opacity: 0.16; filter: blur(10px); }
        }
        @keyframes poemLift {
          0% { opacity: 0; transform: translateY(20px); }
          100% { opacity: 1; transform: translateY(0); }
        }
        .ceramic-ambient-wrap {
          position: absolute;
          width: clamp(180px, 22vw, 320px);
          height: clamp(180px, 22vw, 320px);
          right: clamp(-40px, 2vw, 20px);
          top: 160px;
          pointer-events: none;
          z-index: 1;
        }
        .ceramic-ambient-core {
          position: absolute;
          inset: 12%;
          border-radius: 40% 55% 48% 52%;
          background: radial-gradient(circle at 35% 30%, ${shade(SK.warmPeach, 8)}, ${shade(SK.ceramics, -18)} 68%);
          opacity: 0.28;
          animation: ceramicTurn 34s linear infinite;
        }
        .ceramic-ambient-ring {
          position: absolute;
          inset: 0;
          border-radius: 50%;
          border: 1px solid ${SK.ceramics}55;
          opacity: 0.42;
          animation: ceramicTurn 44s linear reverse infinite;
        }
        .poetry-ambient-path {
          stroke-dasharray: 1400;
          stroke-dashoffset: 1400;
          animation: poetryTrace 30s linear infinite;
        }
        .print-ink-spread {
          position: absolute;
          inset: 0;
          pointer-events: none;
          z-index: 1;
        }
        .print-ink-spread span {
          position: absolute;
          border-radius: 50%;
          background: ${SK.inkDeep};
          mix-blend-mode: multiply;
          opacity: 0;
          animation: printSpread 1300ms ${SK.ease} forwards;
        }
        .print-ink-spread span:nth-child(1) {
          width: 360px; height: 260px; left: 8%; top: 180px;
        }
        .print-ink-spread span:nth-child(2) {
          width: 420px; height: 280px; right: 4%; top: 260px; animation-delay: 130ms;
        }
        .print-ink-spread span:nth-child(3) {
          width: 300px; height: 220px; left: 40%; top: 120px; animation-delay: 220ms;
        }
        @media (max-width: 980px) {
          .works-header, .painting-featured, .painting-alt-row, .print-hero { grid-template-columns: 1fr !important; gap: 24px !important; }
          .painting-alt-row > div { order: initial !important; }
          .painting-alt-row > div:first-child { order: 2 !important; }
          .painting-alt-row > div:last-child { order: 1 !important; }
          .painting-alt-row > div { justify-self: center !important; text-align: center !important; }
          .painting-alt-row > div:first-child { width: 100% !important; justify-content: center !important; }
          .painting-alt-row > div:first-child button { justify-content: center !important; }
          .painting-alt-row > div:last-child { width: min(520px, 100%) !important; }
          .painting-alt-row > div:last-child div { text-align: center !important; }
          .ceramics-grid { column-count: 2 !important; }
          .photo-grid { grid-template-columns: repeat(2, minmax(0, 1fr)) !important; }
          .print-grid { grid-template-columns: repeat(2, minmax(0, 1fr)) !important; }
          .lightbox-grid { grid-template-columns: 1fr !important; }
          .ceramic-ambient-wrap { display: none; }
        }
        @media (max-width: 680px) {
          .ceramics-grid { column-count: 1 !important; }
          .ceramics-grid figcaption { text-align: center !important; flex-direction: column !important; align-items: center !important; gap: 4px !important; }
          .ceramics-grid figcaption > div:first-child { flex-direction: column !important; align-items: center !important; gap: 5px !important; }
          .photo-grid { grid-template-columns: 1fr !important; }
          .print-grid { grid-template-columns: 1fr !important; }
          .poetry-column { max-width: 100% !important; }
        }
        @media (prefers-reduced-motion: reduce) {
          .ceramic-ambient-core, .ceramic-ambient-ring, .poetry-ambient-path, .print-ink-spread span, .poem-page {
            animation: none !important;
          }
        }
      `}</style>
    </div>
  );
}

function Works({ go, activeMedium, setActiveMedium, topOffset = 0 }) {
  const [lightboxItem, setLightboxItem] = React.useState(null);
  React.useEffect(() => setLightboxItem(null), [activeMedium]);
  const accent = WORKS_META[activeMedium]?.accent || SK.painting;

  return (
    <div style={{
      position:'relative', width:'100%', minHeight:'100vh',
      background: SK.paper, color: SK.ink, fontFamily: SK.body, overflow:'hidden',
      paddingTop: topOffset,
    }} data-cursor-tone={accent}>
      <WorksAmbient medium={activeMedium}/>

      <MediumSwitcher active={activeMedium} setActive={setActiveMedium}/>
      <WorksHeader medium={activeMedium}/>

      {activeMedium === 'painting' && <PaintingSection onOpen={setLightboxItem}/>}
      {activeMedium === 'ceramics' && <CeramicsSection onOpen={setLightboxItem}/>}
      {activeMedium === 'poetry' && <PoetrySection/>}
      {activeMedium === 'printmaking' && <PrintsSection onOpen={setLightboxItem}/>}
      {activeMedium === 'photography' && <PrintmakingSection onOpen={setLightboxItem} works={PHOTOGRAPHY_WORKS} tone={SK.photography} featuredLabel="Featured photograph"/>}

      <WorksFooter activeMedium={activeMedium} setActiveMedium={setActiveMedium} go={go}/>
      <WorksLightbox item={lightboxItem} onClose={() => setLightboxItem(null)}/>

      <style>{`
        @keyframes ceramicTurn {
          0% { transform: rotate(0deg) scale(1); }
          50% { transform: rotate(180deg) scale(1.05); }
          100% { transform: rotate(360deg) scale(1); }
        }
        @keyframes poetryTrace {
          0% { stroke-dashoffset: 1400; opacity: 0.35; }
          30% { opacity: 0.65; }
          60% { opacity: 0.55; }
          100% { stroke-dashoffset: 0; opacity: 0.32; }
        }
        @keyframes printSpread {
          0% { transform: scale(0.35); opacity: 0; filter: blur(20px); }
          55% { opacity: 0.24; filter: blur(14px); }
          100% { transform: scale(1); opacity: 0.16; filter: blur(10px); }
        }
        @keyframes poemLift {
          0% { opacity: 0; transform: translateY(20px); }
          100% { opacity: 1; transform: translateY(0); }
        }
        .ceramic-ambient-wrap {
          position: absolute;
          width: clamp(180px, 22vw, 320px);
          height: clamp(180px, 22vw, 320px);
          right: clamp(-40px, 2vw, 20px);
          top: 160px;
          pointer-events: none;
          z-index: 1;
        }
        .ceramic-ambient-core {
          position: absolute;
          inset: 12%;
          border-radius: 40% 55% 48% 52%;
          background: radial-gradient(circle at 35% 30%, ${shade(SK.warmPeach, 8)}, ${shade(SK.ceramics, -18)} 68%);
          opacity: 0.28;
          animation: ceramicTurn 34s linear infinite;
        }
        .ceramic-ambient-ring {
          position: absolute;
          inset: 0;
          border-radius: 50%;
          border: 1px solid ${SK.ceramics}55;
          opacity: 0.42;
          animation: ceramicTurn 44s linear reverse infinite;
        }
        .poetry-ambient-ink {
          position: fixed;
          left: 0;
          right: 0;
          bottom: 0;
          width: 100%;
          height: 140px;
          pointer-events: none;
          opacity: 0.36;
          z-index: 1;
        }
        .poetry-ambient-path {
          stroke-dasharray: 1400;
          stroke-dashoffset: 1400;
          animation: poetryTrace 30s linear infinite;
        }
        .print-ink-spread {
          position: absolute;
          inset: 0;
          pointer-events: none;
          z-index: 1;
        }
        .print-ink-spread span {
          position: absolute;
          border-radius: 50%;
          background: ${SK.inkDeep};
          mix-blend-mode: multiply;
          opacity: 0;
          animation: printSpread 1300ms ${SK.ease} forwards;
        }
        .print-ink-spread span:nth-child(1) {
          width: 360px; height: 260px; left: 8%; top: 180px;
        }
        .print-ink-spread span:nth-child(2) {
          width: 420px; height: 280px; right: 4%; top: 260px; animation-delay: 130ms;
        }
        .print-ink-spread span:nth-child(3) {
          width: 300px; height: 220px; left: 40%; top: 120px; animation-delay: 220ms;
        }
        @media (max-width: 980px) {
          .works-header, .painting-featured, .painting-alt-row, .print-hero { grid-template-columns: 1fr !important; gap: 24px !important; }
          .painting-alt-row > div { order: initial !important; }
          .painting-alt-row > div:first-child { order: 2 !important; }
          .painting-alt-row > div:last-child { order: 1 !important; }
          .painting-alt-row > div { justify-self: center !important; text-align: center !important; }
          .painting-alt-row > div:first-child { width: 100% !important; justify-content: center !important; }
          .painting-alt-row > div:first-child button { justify-content: center !important; }
          .painting-alt-row > div:last-child { width: min(520px, 100%) !important; }
          .painting-alt-row > div:last-child div { text-align: center !important; }
          .ceramics-grid { column-count: 2 !important; }
          .photo-grid { grid-template-columns: repeat(2, minmax(0, 1fr)) !important; }
          .print-grid { grid-template-columns: repeat(2, minmax(0, 1fr)) !important; }
          .lightbox-grid { grid-template-columns: 1fr !important; }
          .ceramic-ambient-wrap { display: none; }
        }
        @media (max-width: 680px) {
          .ceramics-grid { column-count: 1 !important; }
          .ceramics-grid figcaption { text-align: center !important; flex-direction: column !important; align-items: center !important; gap: 4px !important; }
          .ceramics-grid figcaption > div:first-child { flex-direction: column !important; align-items: center !important; gap: 5px !important; }
          .photo-grid { grid-template-columns: 1fr !important; }
          .print-grid { grid-template-columns: 1fr !important; }
          .poetry-column { max-width: 100% !important; }
        }
        @media (prefers-reduced-motion: reduce) {
          .ceramic-ambient-core, .ceramic-ambient-ring, .poetry-ambient-path, .print-ink-spread span, .poem-page {
            animation: none !important;
          }
        }
      `}</style>
    </div>
  );
}

/* ============================================================
   ABOUT
   ============================================================ */

function About({ go }) {
  const blobs = [
    { color: SK.poetry, x: 85, y: 25, r: 180, drift: 32, dx: -12, dy: 14 },
    { color: SK.sienna, x: 15, y: 80, r: 200, drift: 28, dx: 14, dy: -10, delay: 3 },
  ];
  return (
    <div style={{
      position:'relative', width:'100%', minHeight:'100vh',
      background: SK.paper, color: SK.ink, fontFamily: SK.body,
    }} data-cursor-tone={SK.poetry}>
      <WatercolorWash blobs={blobs} opacity={0.3} displaceId="about"/>
      <PaperGrain opacity={0.55} seed={4}/>

      <div style={{padding:'120px clamp(20px, 4vw, 56px) 32px'}}>
        <div style={{
          fontFamily: SK.mono, fontSize: 11, letterSpacing:'0.18em',
          textTransform:'uppercase', color: SK.inkMute, marginBottom: 16,
        }}>
          <span style={{display:'inline-block',width:24,height:1,background:SK.inkMute,verticalAlign:'middle',marginRight:10}}/>
          Hello / a few honest things
        </div>
        <h1 style={{
          fontFamily: SK.display, fontWeight: 400,
          fontSize: 'clamp(64px, 11vw, 132px)', lineHeight: 0.92, letterSpacing:'-0.02em', margin: 0, color: SK.ink,
        }}>
          About <span style={{fontStyle:'italic', color: SK.poetry}}>Sofia</span>
        </h1>
      </div>

      <div className="about-body" style={{padding:'48px clamp(20px, 4vw, 56px) 80px', display:'grid', gridTemplateColumns:'1fr 1.3fr', gap: 64, alignItems:'stretch'}}>
        <div className="about-photo-cell" style={{position:'relative', height:'100%', display:'flex', alignItems:'flex-start', justifyContent:'flex-start'}}>
          <div data-cursor="view" data-cursor-label={"head-\nshot"} style={{
            position:'relative', height: '100%', aspectRatio:'3/4', maxWidth:'100%', width:'auto',
            boxShadow: `0 20px 50px -16px ${SK.ink}66, 0 0 0 10px ${SK.paper}, 0 0 0 11px ${SK.paperDeep}`,
            transform:'rotate(-1.5deg)',
            overflow:'hidden',
          }}>
            <img
              src="assets/works/headshot.jpg"
              alt="Headshot of Sofia Kamal"
              loading="eager"
              style={{
                width:'100%',
                height:'100%',
                objectFit:'cover',
                objectPosition:'50% 38%',
                display:'block',
              }}
            />
          </div>

        </div>

        <div style={{paddingTop: 8, fontFamily: SK.body, fontSize: 17, lineHeight: 1.7, color: SK.inkSoft, maxWidth: 640}}>
          <p style={{margin: '0 0 22px', fontFamily: SK.bodySerif, fontStyle:'italic', fontSize: 24, lineHeight: 1.4, color: SK.ink}}>
            My name is Sofia Kamal.
          </p>
          <p style={{margin: '0 0 22px', fontFamily: SK.bodySerif, fontStyle:'italic', fontSize: 22, lineHeight: 1.5, color: SK.ink}}>
            I’m a Pakistani Muslim writer, born and raised in Phoenix, Arizona — currently studying mathematics and art practice at Stanford University.
          </p>
          <p style={{margin: '0 0 18px'}}>
            My poems have been published by the{' '}
            <a href="https://poets.org/poet/sofia-kamal" target="_blank" rel="noreferrer"
               data-cursor-tone={SK.poetry}
               style={{color: SK.poetry, fontWeight: 500, textDecoration:'underline', textUnderlineOffset:'3px', textDecorationThickness:'1px'}}>
              Academy of American Poets
            </a>{' '}and in{' '}
            <a href="https://www.imls.gov/our-work/partnerships/national-student-poets-program" target="_blank" rel="noreferrer"
               data-cursor-tone={SK.poetry}
               style={{color: SK.poetry, fontStyle:'italic', textDecoration:'underline', textUnderlineOffset:'3px', textDecorationThickness:'1px'}}>
              Poems from the 2024 National Student Poets
            </a>, among others. I was invited to speak at the Academy of American Poets’{' '}
            <a href="https://poets.org/gala/2025" target="_blank" rel="noreferrer"
               data-cursor-tone={SK.poetry}
               style={{color: SK.poetry, fontStyle:'italic', textDecoration:'underline', textUnderlineOffset:'3px', textDecorationThickness:'1px'}}>
              2025 Gala for Poetry &amp; the Creative Mind
            </a>.
          </p>
          <p style={{margin: '0 0 18px'}}>
            My writing and visual art have been recognized by the <strong style={{color: SK.painting, fontWeight: 500}}>Scholastic Art and Writing Awards</strong>, <strong style={{color: SK.ceramics, fontWeight: 500}}>YoungArts</strong>, <em>The Adroit Journal</em>’s Summer Mentorship Program, and the Tempe Festival of the Arts.
          </p>
          <p style={{margin: '0 0 0'}}>
            I served as the 2024 <strong style={{color: SK.poetry, fontWeight: 500}}>National Student Poet of the Southwest</strong>, and as an editor for the student-run literary magazine <em>Pegasus</em>.
          </p>

          {/* Contact / Say hello — stacked under the bio in the right column */}
          <section style={{
            marginTop: 64, paddingTop: 40,
            borderTop:`1px solid ${SK.border}`,
          }} data-cursor-tone={SK.sienna}>
            <div style={{
              fontFamily: SK.mono, fontSize: 11, letterSpacing:'0.18em',
              textTransform:'uppercase', color: SK.inkMute, marginBottom: 14,
            }}>
              <span style={{display:'inline-block',width:24,height:1,background:SK.inkMute,verticalAlign:'middle',marginRight:10}}/>
              Contact / write me
            </div>
            <h2 style={{
              fontFamily: SK.display, fontWeight: 400,
              fontSize: 'clamp(40px, 6vw, 72px)', lineHeight: 0.92,
              letterSpacing:'-0.02em', margin: 0, color: SK.ink,
            }}>
              Say <span style={{fontStyle:'italic', color: SK.sienna}}>hello.</span>
            </h2>
            <div className="about-contact-grid" style={{
              marginTop: 32,
              display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(200px, 1fr))', gap: 24,
              paddingTop: 24, borderTop: `1px solid ${SK.border}`,
            }}>
              <a href="mailto:sofiakamal06@gmail.com" data-cursor-tone={SK.sienna}
                 style={{textDecoration:'none', color:'inherit', display:'block'}}>
                <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.18em', textTransform:'uppercase', color: SK.inkMute, marginBottom: 6}}>Email</div>
                <div style={{fontFamily: SK.display, fontStyle:'italic', fontSize: 19, color: SK.ink}}>sofiakamal06@gmail.com</div>
              </a>
              <a href="mailto:skamal29@stanford.edu" data-cursor-tone={SK.sienna}
                 style={{textDecoration:'none', color:'inherit', display:'block'}}>
                <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.18em', textTransform:'uppercase', color: SK.inkMute, marginBottom: 6}}>School Email</div>
                <div style={{fontFamily: SK.display, fontStyle:'italic', fontSize: 19, color: SK.ink}}>skamal29@stanford.edu</div>
              </a>
              <div>
                <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.18em', textTransform:'uppercase', color: SK.inkMute, marginBottom: 6}}>Currently Living</div>
                <div style={{fontFamily: SK.display, fontStyle:'italic', fontSize: 19, color: SK.ink}}>Palo Alto, CA</div>
              </div>
            </div>
          </section>
        </div>
      </div>

      <div style={{padding:'40px clamp(20px, 4vw, 56px) 60px', borderTop:`1px solid ${SK.ink}22`, display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:16}}>
        <a href="#" onClick={(e) => { e.preventDefault(); go('works'); }} style={{
          fontFamily: SK.mono, fontSize: 11, letterSpacing:'0.16em', textTransform:'uppercase', color: SK.inkMute, textDecoration:'none',
        }}>↩ Back to works</a>
        <div style={{fontFamily: SK.body, fontSize: 13, color: SK.inkMute}}>
          Next →{' '}
          <a href="#" onClick={(e) => { e.preventDefault(); go('practice'); }} style={{color: SK.terracotta, fontFamily: SK.display, fontStyle:'italic', fontSize: 22, textDecoration: 'none'}}>
            Resume
          </a>
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .about-body { grid-template-columns: 1fr !important; gap: 40px !important; align-items: start !important; }
          .about-photo-cell { height: auto !important; }
          .about-photo-cell > div { height: auto !important; width: 100% !important; max-width: 380px !important; }
        }
      `}</style>
    </div>
  );
}

/* ============================================================
   CV / PRACTICE
   ============================================================ */
function CV({ go }) {
  const blobs = [
    { color: SK.terracotta, x: 92, y: 8, r: 120, drift: 30, dx: -8, dy: 10 },
  ];
  const resumeSections = [
    {
      label: 'Education',
      entries: [
        {
          date: '2029',
          title: 'Stanford University',
          location: 'Stanford, CA',
          role: 'Bachelor of Arts, Art Practice',
          details: [
            'Relevant Coursework: Introduction to IDA: Power, Art, and Practice; Conjure Art 101: Performances of Ritual, Spirituality and Decolonial Black Feminist Magic; Math 51; Entrepreneurial Thought Leaders’ Seminar; Painting Off the Wall; Light and Shadow II',
          ],
        },
        {
          date: '2025',
          title: 'Rancho Solano Preparatory School',
          location: 'Phoenix, AZ',
          role: 'GPA: 4.47',
          details: [
            'IB Diploma Recipient, Honor Roll',
            'Recipient of English Department Award (2025)',
          ],
        },
      ],
    },
    {
      label: 'Leadership & Volunteerism',
      entries: [
        {
          date: 'September 2024-August 2025',
          title: 'National Student Poets Program',
          role: 'National Student Poet of the Southwest',
          details: [
            'Organized service project, a series of poetry open mic nights as fundraisers for humanitarian aid in war zones, raising $1085 for Islamic Relief and Middle East Children’s Alliance',
            'Performed at the Kennedy Center (November 2024) and Carnegie Hall (June 2025)',
          ],
        },
        {
          date: 'Summer 2024',
          title: 'CIRCLE Women',
          location: 'Lahore, Pakistan',
          role: 'Intern',
          details: [
            'Internship at CIRCLE, a nonprofit organization in Pakistan with the goal of empowering women through digital literacy and entrepreneurial skills, pulling women out of poverty and encouraging financial independence',
            'Worked with the marketing and social media team, focusing on research for future initiatives, expanding CIRCLE beyond Pakistan, increasing community engagement/visibility through digital platforms, and budgeting',
            'Assisted in multiple digital literacy workshops for around 30 female business owners, which focused on teaching digital skills and tools to women to expand their businesses',
          ],
        },
        {
          date: 'June 2025',
          title: 'Arizona State University’s Young Adult Writer’s Program',
          location: 'Phoenix, AZ',
          role: 'Workshop Coordinator',
          details: [
            'Planned and conducted a series of poetry workshops for elementary and high school students for ASU’s YAWP summer program',
            'Taught in 2 repeated sessions of the programs, each time leading 2 workshops: one for around 20 elementary students (1st - 5th grade) and one for around 30 middle and high school students (6th - 12th grade)',
          ],
        },
        {
          date: 'December 2025',
          title: 'Fundraising Collaboration with Institute for Diversity in the Arts',
          location: 'Stanford, CA',
          role: 'Project Coordinator',
          details: [
            'Collaborated with Stanford’s IDA on self-directed initiative to host an art market fundraising for Sudan through Islamic Relief',
            'Sold 17 prints of my own and others’ work, raising $425',
          ],
        },
        {
          date: '2023-2025',
          title: 'Pegasus Literary Magazine Editorial Board',
          location: 'Phoenix, AZ',
          role: 'Poetry Editor in Chief',
          details: [
            'Reviewed over 500 poems and other creative writing pieces for acceptance/rejection from Pegasus Volume IX',
            'Pegasus Volume IX received a gold medal from the Columbia Scholastic Press Association, First Place with Special Merit from the American Scholastic Press Association, and REALM First Class from the National Council of Teacher’s of English’s Recognizing Excellence in Art and Literary Magazines Contest',
          ],
        },
        {
          date: '2018-2025',
          title: 'Islamic Center of North East Valley',
          location: 'Phoenix, AZ',
          role: 'Outreach Volunteer',
          details: [
            'Worked for refugee empowerment and aid programs, which involved tutoring, fundraising, donation drives, and setting up library and learning spaces',
            'Set up and helped manage Bake Sales put together by Syrian Refugees: all funds went to supporting Syrian families while celebrating their culture and cooking',
          ],
        },
        {
          date: '2023-2024',
          title: 'Epidemiology Research with PhD Candidate at University of South Florida',
          role: 'Researcher',
          details: [
            'Conducted a literature review on the adverse physical health outcomes of Adverse Childhood Experiences (ACEs) and the gaps in populations studied under Dr. Elba Adriana Campos’s guidance, which involved creating a search strategy for the PubMed database, going through 744 studies generated by search, identifying 46 relevant studies, and then summarizing their findings, ultimately using 30 studies in the review',
          ],
        },
        {
          date: '2021-2023',
          title: 'United Nations Institute for Training and Research',
          location: 'Remote',
          role: 'Intern',
          details: [
            'Document research and archiving responsibilities, assisting with editorial work for the Afghan Fellowship Legacy Project’s forthcoming book',
          ],
        },
        {
          date: '2021-2023',
          title: 'Axis Eye Center LLC.',
          location: 'Phoenix, AZ',
          role: 'Intern',
          details: [
            'Assisted senior patients through paperwork and clinical processes, archived financial files, and shadowed technicians and surgeons',
          ],
        },
        {
          date: '2021-2025',
          title: 'National Art Honors Society',
          location: 'Phoenix, AZ',
          role: 'Social Media Director',
          details: [
            'Worked with other members to set up annual fundraising events',
            'Designed, managed, and painted 2 murals for school community',
            'Planned and assisted in 3 volunteer trips to nearby senior living center, focused on arts and crafts activities for residents',
            'Designed school apparel for sale and posters for school wide visual and performing arts showcase',
            'Took professional photos to document school’s arts-related events throughout school year',
          ],
        },
      ],
    },
    {
      label: 'Arts & Culture Experience',
      entries: [
        {
          date: 'Summer 2023',
          title: 'Adroit Summer Mentorship Program',
          location: 'Remote',
          role: 'Poetry Cohort',
          details: [
            'Accepted into a 6 weeklong program with the Adroit Journal, mentorship under Dana Alsamsam-Fatahi',
          ],
        },
        {
          date: 'January 2024',
          title: 'The Kenyon Review Young Writers Workshop',
          location: 'Remote',
          role: 'Admitted Student, Course: Writing Our Surreal Reality with Mathias Svalina',
          details: [
            'Accepted into a 6 weeklong program to study surrealist writing under Mathias Svalina',
          ],
        },
        {
          date: 'May 2025',
          title: 'Gala for Poetry & the Creative Mind',
          location: 'Remote',
          role: 'Speaker',
          details: [
            'Invited to speak at the Academy of American Poets’ annual Gala fundraiser for poetry month, run by former national poet laureate, Ada Limón',
            'https://poets.org/gala/2025',
          ],
        },
        {
          date: 'November 2024',
          title: 'Louisiana Book Festival',
          location: 'Baton Rouge, LA',
          role: 'Panelist, Speaker',
          details: [
            'Performed poems and spoke in 2 panels on chapbook, Poems from the 2024 National Student Poets',
          ],
        },
        {
          date: '2026',
          title: 'Cantor Arts Center',
          location: 'Stanford, CA',
          role: 'Program Assistant',
          details: [
            'Hired to provide support preparing, coordinating, and staffing on-site academic and public programming, including Family Day, Party on the Edge, Art and Boba Talks, etc.',
          ],
        },
        {
          date: '2023',
          title: 'National Security Language Initiative for Youth (NSLI-Y)',
          location: 'Remote',
          role: 'Scholarship Recipient',
          details: [
            'Virtual language learning scholarship received for 10-week course for Arabic',
          ],
        },
        {
          date: '2023 & 2024',
          title: 'Scholastic Art and Writing Awards',
          role: 'Medalist',
          details: [
            'Silver medal for Drawing and Illustration (2023)',
            'Silver Medal for Photography (2024)',
          ],
        },
        {
          date: '2024',
          title: 'Young Arts',
          role: 'Medalist',
          details: [
            'National Medal for Writing/Short Story',
          ],
        },
      ],
    },
    {
      label: 'Publications',
      entries: [
        {
          date: 'November 2024',
          title: 'Academy of American Poets, poetry.org',
          details: [
            'Poetry publication',
            'https://poets.org/poem/homecoming-augury',
          ],
        },
        {
          date: 'May 2025',
          title: 'Poems from the 2024 National Student Poets',
          details: [
            'Poetry publication',
            'https://www.imls.gov/our-work/partnerships/national-student-poets-program',
          ],
        },
      ],
    },
  ];
  const skillGroups = [
    {
      title: 'Languages',
      text: 'Fluency in English; conversational fluency in Urdu; proficient in Mandarin',
    },
    {
      title: 'Organizing & teaching',
      text: 'Experience/interest in event organizing and fundraising, as well as teaching',
    },
    {
      title: 'Digital',
      text: 'Proficiency with Adobe Photoshop',
    },
    {
      title: 'Photography',
      text: 'Proficiency with Hasselblad 501C camera',
    },
    {
      title: 'Studio interests',
      text: 'Professional interest in visual art (painting, photography, sculpture, etc.)',
    },
  ];
  const Section = ({ label, children }) => (
    <section className="cv-section" style={{display:'grid', gridTemplateColumns:'180px 1fr', gap: 36, padding:'28px 0', borderBottom:`1px solid ${SK.ink}22`}}>
      <div style={{
        fontFamily: SK.mono, fontSize: 11, letterSpacing:'0.18em',
        textTransform:'uppercase', color: SK.terracotta, paddingTop: 4,
      }}>
        {label}
      </div>
      <div>{children}</div>
    </section>
  );
  const Detail = ({ text }) => {
    const isUrl = /^https?:\/\//.test(text);
    if (isUrl) {
      return (
        <a href={text} target="_blank" rel="noreferrer" data-cursor-tone={SK.terracotta} style={{color: SK.terracotta, textDecoration:'none'}}>
          {text}
        </a>
      );
    }
    return <>{text}</>;
  };
  const Entry = ({ date, title, location, role, href, details = [] }) => (
    <div className="cv-entry" style={{display:'grid', gridTemplateColumns:'140px 1fr', gap: 24, padding:'16px 0', alignItems:'baseline'}}>
      <div style={{fontFamily: SK.mono, fontSize: 11, color: SK.inkMute, letterSpacing:'0.04em', lineHeight: 1.45}}>{date}</div>
      <div>
        <div style={{fontFamily: SK.body, fontSize: 15, color: SK.ink, fontWeight: 600, lineHeight: 1.35}}>
          {href ? (
            <a href={href} target="_blank" rel="noreferrer" data-cursor-tone={SK.terracotta} style={{color: SK.ink, textDecoration:'none'}}>
              {title}
            </a>
          ) : title}
          {location && <span style={{fontFamily: SK.bodySerif, fontStyle:'italic', fontWeight:400, color: SK.inkSoft}}> — {location}</span>}
        </div>
        {role && <div style={{fontFamily: SK.bodySerif, fontStyle:'italic', fontSize: 14, color: SK.inkSoft, marginTop: 3, lineHeight: 1.45}}>{role}</div>}
        {!!details.length && (
          <ul style={{margin:'8px 0 0', paddingLeft: 18, fontFamily: SK.body, fontSize: 13, color: SK.inkMute, lineHeight: 1.58}}>
            {details.map((detail, i) => <li key={i} style={{marginBottom: 4}}><Detail text={detail}/></li>)}
          </ul>
        )}
      </div>
    </div>
  );
  return (
    <div style={{
      position:'relative', width:'100%', minHeight:'100vh',
      background: SK.paper, color: SK.ink, fontFamily: SK.body,
    }} data-cursor-tone={SK.terracotta}>
      <WatercolorWash blobs={blobs} opacity={0.25} displaceId="cv"/>
      <PaperGrain opacity={0.5} seed={5}/>

      <div className="cv-header" style={{padding:'120px clamp(20px, 4vw, 56px) 32px', display:'grid', gridTemplateColumns:'1.4fr 1fr', gap: 48, alignItems:'end'}}>
        <div>
          <div style={{fontFamily: SK.mono, fontSize: 11, letterSpacing:'0.18em', textTransform:'uppercase', color: SK.inkMute, marginBottom: 14}}>
            <span style={{display:'inline-block',width:24,height:1,background:SK.inkMute,verticalAlign:'middle',marginRight:10}}/>
            Resume
          </div>
          <h1 style={{
            fontFamily: SK.display, fontWeight: 400,
            fontSize: 'clamp(56px, 9vw, 116px)', lineHeight: 0.9, letterSpacing:'-0.02em', margin: 0, color: SK.ink,
          }}>
            <span style={{fontStyle:'italic'}}>Resume</span>
          </h1>
        </div>
        <div>
          <div style={{
            background: SK.paperDeep, padding: '20px 22px',
            border: `1px solid ${SK.ink}33`,
            position:'relative',
          }}>
            <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.16em', textTransform:'uppercase', color: SK.inkMute, marginBottom: 10}}>
              Contact
            </div>
            <div style={{display:'grid', gap: 10, fontFamily: SK.body, fontSize: 14, color: SK.ink}}>
              <div>Stanford, CA</div>
              <a href="mailto:sofiakamal06@gmail.com" data-cursor-tone={SK.terracotta} style={{color: SK.ink, textDecoration:'none'}}>sofiakamal06@gmail.com</a>
            </div>
            <div style={{display:'flex', flexDirection:'column', gap: 10, marginTop: 16}}>
              {[
                {n:'Resume (PDF)', s:'download', href:'assets/resume.pdf'},
              ].map(d => (
                <div key={d.n} style={{display:'flex', alignItems:'center', justifyContent:'space-between', padding:'10px 0', borderTop: `1px dashed ${SK.ink}33`}}>
                  <div>
                    <div style={{fontFamily: SK.body, fontSize: 14, color: SK.ink, fontWeight: 500}}>{d.n}</div>
                    <div style={{fontFamily: SK.mono, fontSize: 10, color: SK.inkMute, letterSpacing:'0.08em', marginTop: 2}}>{d.s}</div>
                  </div>
                  <a href={d.href} download="" data-cursor="view" data-cursor-label="download" data-cursor-tone={SK.terracotta} style={{
                    width: 36, height: 36, borderRadius: '50%',
                    background: SK.terracotta, color: SK.paper,
                    display:'flex', alignItems:'center', justifyContent:'center',
                    textDecoration:'none', flexShrink: 0,
                  }}>
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 2v8m0 0L3 6m4 4l4-4M2 12h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </a>
                </div>
              ))}
            </div>
          </div>
          <div style={{marginTop: 14, fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.14em', textTransform:'uppercase', color: SK.inkMute, textAlign:'right'}}>
            Source resume · 05 / 2026
          </div>
        </div>
      </div>

      <div style={{padding:'24px clamp(20px, 4vw, 56px) 56px'}}>
        {resumeSections.map(section => (
          <Section key={section.label} label={section.label}>
            {section.entries.map((entry, i) => <Entry key={`${section.label}-${i}`} {...entry}/>)}
          </Section>
        ))}
        <Section label="Skills & Interests">
          <div className="cv-skills" style={{display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap: 22, paddingTop: 8}}>
            {skillGroups.map(group => (
              <div key={group.title} style={{background:`${SK.paperDeep}88`, border:`1px solid ${SK.ink}1f`, padding:'16px 18px'}}>
                <div style={{fontFamily: SK.mono, fontSize: 10, color: SK.terracotta, letterSpacing:'0.14em', textTransform:'uppercase', marginBottom: 7}}>{group.title}</div>
                <div style={{fontFamily: SK.body, fontSize: 13, color: SK.inkSoft, lineHeight: 1.62}}>
                  {group.text}
                </div>
              </div>
            ))}
          </div>
        </Section>
      </div>

      <div style={{padding:'32px clamp(20px, 4vw, 56px) 56px', borderTop: `2px solid ${SK.ink}`, display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:16}}>
        <a href="#" onClick={(e) => { e.preventDefault(); go('works'); }} style={{fontFamily: SK.display, fontStyle:'italic', fontSize: 24, color: SK.terracotta, textDecoration:'none'}}>sofia kamal</a>
        <div style={{fontFamily: SK.mono, fontSize: 11, letterSpacing:'0.18em', textTransform:'uppercase', color: SK.inkMute, textAlign:'right'}}>
          <a href="mailto:sofiakamal06@gmail.com" style={{color: SK.inkMute, textDecoration:'none'}}>sofiakamal06@gmail.com</a>
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .cv-header { grid-template-columns: 1fr !important; align-items: start !important; }
          .cv-section { grid-template-columns: 1fr !important; gap: 12px !important; }
          .cv-skills { grid-template-columns: 1fr !important; }
          .cv-entry { grid-template-columns: 1fr !important; gap: 5px !important; }
        }
      `}</style>
    </div>
  );
}

/* ============================================================
   CONTACT (small page)
   ============================================================ */
function Contact({ go }) {
  const blobs = [
    { color: SK.sienna, x: 20, y: 30, r: 220, drift: 28, dx: 12, dy: -8 },
    { color: SK.warmPeach, x: 80, y: 70, r: 240, drift: 32, dx: -10, dy: 14, delay: 2 },
  ];
  return (
    <div style={{
      position:'relative', width:'100%', minHeight:'100vh',
      background: SK.paper, color: SK.ink, fontFamily: SK.body,
    }} data-cursor-tone={SK.sienna}>
      <WatercolorWash blobs={blobs} opacity={0.3} displaceId="contact"/>
      <PaperGrain opacity={0.5} seed={6}/>
      <div style={{padding:'140px clamp(20px, 4vw, 56px) 80px', maxWidth: 920}}>
        <div style={{fontFamily: SK.mono, fontSize: 11, letterSpacing:'0.18em', textTransform:'uppercase', color: SK.inkMute, marginBottom: 16}}>
          <span style={{display:'inline-block',width:24,height:1,background:SK.inkMute,verticalAlign:'middle',marginRight:10}}/>
          Contact / write me
        </div>
        <h1 style={{
          fontFamily: SK.display, fontWeight: 400,
          fontSize: 'clamp(56px, 10vw, 132px)', lineHeight: 0.92, letterSpacing:'-0.02em', margin: 0, color: SK.ink,
        }}>
          Say <span style={{fontStyle:'italic', color: SK.sienna}}>hello.</span>
        </h1>
        <p style={{fontFamily: SK.bodySerif, fontStyle:'italic', fontSize: 22, lineHeight: 1.5, color: SK.inkSoft, maxWidth: 600, marginTop: 32}}>
          For studio visits, exhibitions, commissions, or just to send a poem — write to me. The kiln is usually warm. Replies come within a week, slower in the summer.
        </p>
        <div style={{marginTop: 56, display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(220px, 1fr))', gap: 32, paddingTop: 32, borderTop: `1px solid ${SK.border}`}}>
          {[
            ['Email','sofiakamal06@gmail.com','mailto:sofiakamal06@gmail.com'],
            ['Studio','Roble Hall, B-12 · Stanford',''],
            ['Instagram','@sofiakamal','https://instagram.com/'],
            ['Phone','+1 (650) 555 — 0148','tel:+16505550148'],
          ].map(([k,v,h]) => (
            <a key={k} href={h || '#'} target={h?.startsWith('http') ? '_blank' : undefined} rel="noreferrer"
              style={{textDecoration:'none', color:'inherit', display:'block'}}>
              <div style={{fontFamily: SK.mono, fontSize: 10, letterSpacing:'0.18em', textTransform:'uppercase', color: SK.inkMute, marginBottom: 6}}>{k}</div>
              <div style={{fontFamily: SK.display, fontStyle:'italic', fontSize: 22, color: SK.ink}}>{v}</div>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   NAVIGATION + TRANSITION
   ============================================================ */
function WashTransition({ phase, color }) {
  const active = phase === 'covering' || phase === 'covered';
  return (
    <div style={{
      position:'fixed', inset:0, zIndex: 9000, pointerEvents:'none',
      opacity: active ? 1 : 0,
      transition: `opacity 800ms ${SK.ease}`,
    }}>
      <svg style={{position:'absolute',inset:0,width:'100%',height:'100%'}} aria-hidden>
        <defs>
          <filter id="wash-disp" x="-20%" y="-20%" width="140%" height="140%">
            <feTurbulence type="fractalNoise" baseFrequency="0.014" numOctaves="2" seed="9"/>
            <feDisplacementMap in="SourceGraphic" scale="60"/>
            <feGaussianBlur stdDeviation="14"/>
          </filter>
        </defs>
        <g filter="url(#wash-disp)" opacity="0.92">
          <ellipse cx={active ? '50%' : '40%'} cy="55%" rx="65%" ry="55%" fill={color} style={{
            mixBlendMode:'multiply',
            transition:`all 800ms ${SK.ease}`,
            transform: active ? 'scale(1.4)' : 'scale(0.6)',
            transformOrigin:'center',
          }}/>
        </g>
      </svg>
      <div style={{position:'absolute', inset:0, background: `${color}11`}}/>
    </div>
  );
}

/* ============================================================
   APP ROOT (multi-page)
   ============================================================ */
const ROUTE_TO_FILE = {
  home: 'index.html',
  works: 'works.html',
  about: 'about.html',
  practice: 'practice.html',
};
const ROUTE_TRANSITION_KEY = 'sofia-route-transition';

function readPendingRouteTransition() {
  if (typeof sessionStorage === 'undefined') return null;
  try {
    const raw = sessionStorage.getItem(ROUTE_TRANSITION_KEY);
    if (!raw) return null;
    sessionStorage.removeItem(ROUTE_TRANSITION_KEY);
    const data = JSON.parse(raw);
    if (!data || !data.color) return null;
    return data;
  } catch (e) {
    return null;
  }
}

function getRouteFromPage() {
  const fromBody = document.body.dataset.page;
  if (fromBody && ROUTE_TO_FILE[fromBody]) return fromBody;
  const file = (location.pathname.split('/').pop() || 'index.html').toLowerCase();
  if (file === 'index.html' || file === '') return 'home';
  if (file === 'works.html') return 'works';
  if (file === 'about.html') return 'about';
  if (file === 'practice.html') return 'practice';
  if (file === 'contact.html') return 'about';
  return 'home';
}

function TopBreadcrumb({ visible, onTop }) {
  return (
    <button
      onClick={onTop}
      aria-label="Go to top"
      data-cursor-tone={SK.sienna}
      style={{
        position:'fixed',
        top: 10,
        left:'50%',
        transform: visible ? 'translateX(-50%) translateY(0)' : 'translateX(-50%) translateY(-14px)',
        opacity: visible ? 1 : 0,
        pointerEvents: visible ? 'auto' : 'none',
        zIndex: 1200,
        background: `${SK.paper}f0`,
        color: SK.sienna,
        border: `1px solid ${SK.border}`,
        borderRadius: 999,
        padding:'8px 14px',
        display:'flex',
        alignItems:'center',
        gap: 8,
        fontFamily: SK.mono,
        fontSize: 10,
        letterSpacing:'0.16em',
        textTransform:'uppercase',
        backdropFilter:'blur(6px)',
        boxShadow:`0 10px 22px -14px ${SK.ink}99`,
        transition:`opacity 320ms ${SK.ease}, transform 320ms ${SK.ease}, background 320ms ${SK.ease}`,
        cursor:'none',
      }}
    >
      <span style={{
        width:18,
        height:18,
        borderRadius:'50%',
        background: `${SK.sienna}18`,
        display:'inline-flex',
        alignItems:'center',
        justifyContent:'center',
      }}>
        <svg width="9" height="9" viewBox="0 0 10 10" fill="none" aria-hidden>
          <path d="M5 9V1M5 1L2.2 3.8M5 1L7.8 3.8" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </span>
      Go to top
    </button>
  );
}

function Root() {
  const route = getRouteFromPage();
  const initialTransition = React.useMemo(() => readPendingRouteTransition(), []);
  const VALID_MEDIA = ['painting','ceramics','poetry','photography','printmaking'];
  const [activeMedium, setActiveMedium] = React.useState(() => {
    const h = (location.hash || '').replace('#','').toLowerCase();
    return VALID_MEDIA.includes(h) ? h : 'painting';
  });
  const [transitionPhase, setTransitionPhase] = React.useState(initialTransition ? 'covered' : 'idle');
  const [transColor, setTransColor] = React.useState(initialTransition?.color || SK.sienna);
  const [showTopCrumb, setShowTopCrumb] = React.useState(false);

  const accentByRoute = (r) => ({
    home: SK.sienna, works: SK.painting, about: SK.poetry,
    practice: SK.terracotta,
  })[r] || SK.sienna;

  const go = (r, hash) => {
    if (!ROUTE_TO_FILE[r]) return;

    if (r === route) {
      if (hash && r === 'works') setActiveMedium(hash);
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }

    const nextColor = accentByRoute(r);
    setTransColor(nextColor);
    setTransitionPhase('covering');
    try {
      sessionStorage.setItem(ROUTE_TRANSITION_KEY, JSON.stringify({ color: nextColor, at: Date.now() }));
    } catch (e) {}
    setTimeout(() => {
      window.location.href = ROUTE_TO_FILE[r] + (hash ? '#' + hash : '');
    }, 400);
    setTimeout(() => setTransitionPhase('idle'), 900);
  };

  React.useEffect(() => {
    if (transitionPhase !== 'covered') return;
    let raf2;
    let done;
    const raf1 = requestAnimationFrame(() => {
      raf2 = requestAnimationFrame(() => {
        setTransitionPhase('revealing');
        done = setTimeout(() => setTransitionPhase('idle'), 850);
      });
    });
    return () => {
      cancelAnimationFrame(raf1);
      if (raf2) cancelAnimationFrame(raf2);
      if (done) clearTimeout(done);
    };
  }, [transitionPhase]);

  React.useEffect(() => {
    const update = () => {
      if (route !== 'home') {
        setShowTopCrumb(false);
        return;
      }
      const threshold = window.innerHeight * 0.92;
      setShowTopCrumb(window.scrollY > threshold);
    };
    update();
    window.addEventListener('scroll', update, { passive: true });
    window.addEventListener('resize', update);
    return () => {
      window.removeEventListener('scroll', update);
      window.removeEventListener('resize', update);
    };
  }, [route]);

  let body;
  if (route === 'home') {
    body = (
      <>
        <Hero go={go} setActiveMedium={setActiveMedium}/>
        <HomeWorksAll go={go}/>
      </>
    );
  } else if (route === 'works') {
    body = <Works go={go} activeMedium={activeMedium} setActiveMedium={setActiveMedium} topOffset={'clamp(62px, 8vh, 96px)'}/>;
  } else if (route === 'about') {
    body = <About go={go}/>;
  } else if (route === 'practice') {
    body = <CV go={go}/>;
  }

  return (
    <>
      <ViewCursor/>
      <TopBreadcrumb visible={showTopCrumb} onTop={() => window.scrollTo({ top: 0, behavior: 'smooth' })}/>
      <div style={{position:'relative'}}>
        <SharedNav route={route} go={go}/>
        {body}
      </div>
      <WashTransition phase={transitionPhase} color={transColor}/>
    </>
  );
}

function SharedNav({ route, go }) {
  const items = [
    {id:'works',    l:'Works',    accent: SK.painting},
    {id:'about',    l:'About',    accent: SK.poetry},
    {id:'practice', l:'Resume', accent: SK.terracotta},
  ];
  return (
    <div style={{
      position:'absolute',
      top:0,
      left:0,
      right:0,
      zIndex: 1000,
      display:'flex',
      alignItems:'center',
      justifyContent:'space-between',
      padding:'24px clamp(20px, 4vw, 56px)',
      pointerEvents:'none',
    }}>
      <a onClick={(e) => { e.preventDefault(); go('home'); }} href="index.html" style={{
        fontFamily: SK.display, fontSize: 'clamp(18px, 1.6vw, 22px)', letterSpacing:'-0.01em',
        fontStyle:'italic', fontWeight: 400, color: SK.ink, textDecoration:'none',
        pointerEvents:'auto',
      }} data-cursor-tone={SK.sienna}>
        sofia kamal
      </a>
      <nav className="sk-nav" style={{
        display:'flex',
        gap:'clamp(20px, 2.6vw, 36px)',
        fontFamily: SK.body,
        fontSize:12,
        letterSpacing:'0.16em',
        textTransform:'uppercase',
        pointerEvents:'auto',
      }}>
        {items.map(({id, l, accent}) => {
          const active = route === id;
          const href = ROUTE_TO_FILE[id];
          return (
            <a key={id} onClick={(e) => { e.preventDefault(); go(id); }} href={href}
              data-cursor-tone={accent}
              style={{color: SK.ink, textDecoration:'none', position:'relative', opacity: active ? 1 : 0.65, transition:`opacity 400ms ${SK.ease}`}}>
              {l}
              {active && <span style={{position:'absolute',left:0,right:0,bottom:-7,height:1.5,background:accent}}/>}
            </a>
          );
        })}
      </nav>
    </div>
  );
}

/* ============================================================
   MOUNT
   ============================================================ */
ReactDOM.createRoot(document.getElementById('root')).render(<Root/>);
