// 22hrs — Progress screen
// Visual treatment tracking: capture, auto-tagged gallery, side-by-side compare, timeline scrub
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

// ──────────────────────────────────────────────
// Treatment photo data
// 84-day mark = today. Captures roughly every 7 days.
// ──────────────────────────────────────────────
const PROGRESS_PHOTOS = [
  { id: 1,  day: 1,  tray: 1,  date: 'Feb 12', time: '8:32 AM',  full: 'Feb 12 · 8:32 AM', tag: 'Baseline' },
  { id: 2,  day: 7,  tray: 1,  date: 'Feb 18', time: '9:14 PM',  full: 'Feb 18 · 9:14 PM' },
  { id: 3,  day: 14, tray: 2,  date: 'Feb 25', time: '7:50 AM',  full: 'Feb 25 · 7:50 AM', tag: 'Tray switch' },
  { id: 4,  day: 21, tray: 3,  date: 'Mar 04', time: '8:02 AM',  full: 'Mar 04 · 8:02 AM' },
  { id: 5,  day: 28, tray: 4,  date: 'Mar 11', time: '8:18 AM',  full: 'Mar 11 · 8:18 AM' },
  { id: 6,  day: 35, tray: 5,  date: 'Mar 18', time: '9:45 PM',  full: 'Mar 18 · 9:45 PM' },
  { id: 7,  day: 42, tray: 6,  date: 'Mar 25', time: '8:11 AM',  full: 'Mar 25 · 8:11 AM', tag: 'Halfway' },
  { id: 8,  day: 49, tray: 7,  date: 'Apr 01', time: '7:55 AM',  full: 'Apr 01 · 7:55 AM' },
  { id: 9,  day: 56, tray: 8,  date: 'Apr 08', time: '8:24 AM',  full: 'Apr 08 · 8:24 AM' },
  { id: 10, day: 63, tray: 9,  date: 'Apr 15', time: '9:30 PM',  full: 'Apr 15 · 9:30 PM' },
  { id: 11, day: 70, tray: 10, date: 'Apr 22', time: '8:09 AM',  full: 'Apr 22 · 8:09 AM' },
  { id: 12, day: 77, tray: 11, date: 'Apr 29', time: '8:46 AM',  full: 'Apr 29 · 8:46 AM' },
  { id: 13, day: 84, tray: 14, date: 'May 06', time: '7:38 AM',  full: 'May 06 · 7:38 AM', tag: 'Latest' },
];
const PLAN_TOTAL_DAYS = 196;

// ──────────────────────────────────────────────
// SmilePhoto — striped placeholder that warms across treatment.
// Strictly a placeholder per design system (no hand-drawn teeth).
// `t` 0..1 indexes how far along treatment the photo is.
// ──────────────────────────────────────────────
function SmilePhoto({ day, tray, t = 0, rounded = 14, captionScale = 1, showCaption = true }) {
  // cool cyan early → warm peach late, low chroma so it reads as photographic fog
  const h1 = 195 - t * 195;   // 195 cyan → 0 peach
  const h2 = 165 - t * 140;   // 165 teal → 25 amber
  const l1 = 0.32 + t * 0.06;
  const l2 = 0.18 + t * 0.04;
  return (
    <div style={{
      position: 'relative', width: '100%', height: '100%',
      borderRadius: rounded, overflow: 'hidden',
      background: `linear-gradient(135deg, oklch(${l1} 0.05 ${h1}) 0%, oklch(${l2} 0.04 ${h2}) 100%)`,
      isolation: 'isolate'
    }}>
      {/* diagonal stripe texture — telegraphs "placeholder" while still feeling photographic */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'repeating-linear-gradient(135deg, transparent 0 14px, rgba(255,255,255,0.045) 14px 15px)'
      }}/>
      {/* center vignette */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at 50% 55%, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0) 60%)'
      }}/>
      {/* corner marker */}
      <div style={{
        position: 'absolute', top: 10, left: 10, width: 6, height: 6, borderRadius: '50%',
        background: 'rgba(255,255,255,0.55)', boxShadow: '0 0 0 1px rgba(0,0,0,0.1)'
      }}/>
      {showCaption && (
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          padding: `${10*captionScale}px ${12*captionScale}px`,
          background: 'linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.5) 100%)',
          color: 'rgba(255,255,255,0.92)',
          fontFamily: 'Geist Mono, monospace',
          fontSize: 10 * captionScale, letterSpacing: '0.06em',
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline'
        }}>
          <span>SMILE · D{day}</span>
          <span style={{ opacity: 0.7 }}>T{tray}</span>
        </div>
      )}
    </div>
  );
}

// ──────────────────────────────────────────────
// PhotoTag chip — used in Capture viewfinder & cards
// ──────────────────────────────────────────────
function PhotoTag({ children, color = 'rgba(255,255,255,0.85)', bg = 'rgba(0,0,0,0.55)' }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '6px 10px', borderRadius: 999,
      background: bg, color,
      fontFamily: 'Geist Mono, monospace', fontSize: 10.5, letterSpacing: '0.04em',
      backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)'
    }}>{children}</div>
  );
}

// ──────────────────────────────────────────────
// Gallery — chronological grid grouped by tray bucket
// ──────────────────────────────────────────────
function GalleryView({ photos, onOpen, onCompare, onCapture }) {
  // group by tray
  const byTray = photos.reduce((acc, p) => {
    (acc[p.tray] = acc[p.tray] || []).push(p);
    return acc;
  }, {});
  const trays = Object.keys(byTray).sort((a,b)=>+b-+a); // newest tray first

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Latest hero */}
      <Card padding={14}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <Eyebrow>Latest capture</Eyebrow>
          <span style={{ fontSize: 11, color: 'var(--t-fg-muted)' }}>13 of 28 captures</span>
        </div>
        <div style={{ position:'relative', width:'100%', aspectRatio:'4/3' }}>
          <SmilePhoto day={photos[photos.length-1].day} tray={photos[photos.length-1].tray} t={1} rounded={12} showCaption={false}/>
          <div style={{ position:'absolute', top:10, right:10, display:'flex', gap:6 }}>
            <PhotoTag bg="rgba(31,184,224,0.78)" color="#fff">D{photos[photos.length-1].day}</PhotoTag>
            <PhotoTag bg="rgba(60,191,158,0.78)" color="#fff">T{photos[photos.length-1].tray}</PhotoTag>
          </div>
          <div style={{ position:'absolute', left:12, bottom:10, color:'#fff', fontFamily:'Geist Mono, monospace', fontSize:11, letterSpacing:'0.04em', textShadow:'0 1px 2px rgba(0,0,0,0.5)' }}>
            {photos[photos.length-1].full}
          </div>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:12 }}>
          <Btn variant="quiet" block onClick={() => onCompare(photos[0].id, photos[photos.length-1].id)}>Compare with day 1</Btn>
          <Btn variant="primary" block onClick={onCapture}
            leading={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>}>
            New capture
          </Btn>
        </div>
      </Card>

      {/* By-tray groups */}
      {trays.map(tray => (
        <div key={tray}>
          <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:8, paddingLeft:2 }}>
            <Eyebrow>Tray {tray}</Eyebrow>
            <span style={{ fontSize:11, color:'var(--t-fg-muted)', fontVariantNumeric:'tabular-nums' }}>{byTray[tray].length} photo{byTray[tray].length>1?'s':''}</span>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
            {byTray[tray].sort((a,b)=>b.day-a.day).map(p => (
              <div key={p.id} onClick={() => onOpen(p.id)} style={{ cursor:'pointer' }}>
                <div style={{ position:'relative', width:'100%', aspectRatio:'1/1', borderRadius:12, overflow:'hidden' }}>
                  <SmilePhoto day={p.day} tray={p.tray} t={p.day / PLAN_TOTAL_DAYS} rounded={12} showCaption={false}/>
                  {p.tag && (
                    <div style={{ position:'absolute', top:8, left:8 }}>
                      <PhotoTag bg="rgba(0,0,0,0.55)" color="rgba(255,255,255,0.9)">{p.tag}</PhotoTag>
                    </div>
                  )}
                </div>
                <div style={{ marginTop:8, display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
                  <div>
                    <div style={{ fontSize:12.5, fontWeight:500, color:'var(--t-fg-1)', fontVariantNumeric:'tabular-nums' }}>Day {p.day}</div>
                    <div style={{ fontSize:11, color:'var(--t-fg-3)', marginTop:2, fontVariantNumeric:'tabular-nums' }}>{p.date}</div>
                  </div>
                  <span style={{ fontSize:10, color:'var(--t-fg-muted)', fontFamily:'Geist Mono, monospace' }}>T{p.tray}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

// ──────────────────────────────────────────────
// Compare — two-photo draggable reveal slider
// ──────────────────────────────────────────────
function CompareView({ photos, leftId, rightId, onPick }) {
  const left  = photos.find(p => p.id === leftId)  || photos[0];
  const right = photos.find(p => p.id === rightId) || photos[photos.length-1];
  const [pos, setPos] = useStateP(50); // 0..100 — % of width showing LEFT
  const wrapRef = useRefP(null);
  const dragging = useRefP(false);

  const move = (clientX) => {
    const el = wrapRef.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const x = Math.max(0, Math.min(r.width, clientX - r.left));
    setPos(x / r.width * 100);
  };
  useEffectP(() => {
    const onMove = (e) => {
      if (!dragging.current) return;
      e.preventDefault();
      const cx = e.touches ? e.touches[0].clientX : e.clientX;
      move(cx);
    };
    const onUp = () => { dragging.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchmove', onMove, { passive: false });
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('touchend', onUp);
    };
  }, []);

  // picker rail
  const Rail = ({ value, onChange, label }) => (
    <div style={{ marginTop:10 }}>
      <div style={{ fontSize:10.5, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--t-fg-muted)', marginBottom:6, fontWeight:500 }}>{label}</div>
      <div style={{ display:'flex', gap:6, overflowX:'auto', paddingBottom:4, scrollbarWidth:'none' }}>
        {photos.map(p => {
          const sel = p.id === value;
          return (
            <button key={p.id} onClick={() => onChange(p.id)} style={{
              flex:'none', position:'relative', width:46, height:46, borderRadius:8,
              border:0, padding:0, cursor:'pointer', overflow:'hidden',
              outline: sel ? '2px solid #1FB8E0' : '1px solid var(--t-border-strong)',
              outlineOffset: sel ? 1 : 0
            }}>
              <SmilePhoto day={p.day} tray={p.tray} t={p.day / PLAN_TOTAL_DAYS} rounded={8} showCaption={false}/>
              <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'flex-end', justifyContent:'center', paddingBottom:2, fontFamily:'Geist Mono, monospace', fontSize:9, color:'#fff', textShadow:'0 1px 2px rgba(0,0,0,0.6)' }}>D{p.day}</div>
            </button>
          );
        })}
      </div>
    </div>
  );

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <Card padding={14}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10 }}>
          <Eyebrow>Side by side</Eyebrow>
          <span style={{ fontSize:11, color:'var(--t-fg-muted)', fontVariantNumeric:'tabular-nums' }}>Drag the handle</span>
        </div>

        {/* slider */}
        <div ref={wrapRef}
          onMouseDown={(e) => { dragging.current = true; move(e.clientX); }}
          onTouchStart={(e) => { dragging.current = true; move(e.touches[0].clientX); }}
          style={{
            position:'relative', width:'100%', aspectRatio:'4/5',
            borderRadius:12, overflow:'hidden', userSelect:'none', touchAction:'none', cursor:'ew-resize'
          }}>
          {/* RIGHT photo (full bleed) */}
          <div style={{ position:'absolute', inset:0 }}>
            <SmilePhoto day={right.day} tray={right.tray} t={right.day / PLAN_TOTAL_DAYS} rounded={0} showCaption={false}/>
          </div>
          {/* LEFT photo (clipped) */}
          <div style={{ position:'absolute', inset:0, clipPath: `inset(0 ${100-pos}% 0 0)` }}>
            <SmilePhoto day={left.day} tray={left.tray} t={left.day / PLAN_TOTAL_DAYS} rounded={0} showCaption={false}/>
          </div>
          {/* corner badges */}
          <div style={{ position:'absolute', top:10, left:10 }}>
            <PhotoTag bg="rgba(0,0,0,0.55)" color="#fff">BEFORE · D{left.day}</PhotoTag>
          </div>
          <div style={{ position:'absolute', top:10, right:10 }}>
            <PhotoTag bg="rgba(31,184,224,0.78)" color="#fff">AFTER · D{right.day}</PhotoTag>
          </div>
          {/* handle line */}
          <div style={{
            position:'absolute', top:0, bottom:0, left: pos + '%',
            width:2, transform:'translateX(-1px)',
            background:'#FFFFFF', boxShadow:'0 0 18px rgba(0,0,0,0.4)'
          }}/>
          {/* handle puck */}
          <div style={{
            position:'absolute', top:'50%', left: pos + '%',
            transform:'translate(-50%,-50%)',
            width:38, height:38, borderRadius:'50%',
            background:'#FFFFFF', boxShadow:'0 4px 12px rgba(0,0,0,0.35)',
            display:'flex', alignItems:'center', justifyContent:'center', gap:2
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#0E1014" strokeWidth="2.2" strokeLinecap="round"><polyline points="15 18 9 12 15 6"/></svg>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#0E1014" strokeWidth="2.2" strokeLinecap="round"><polyline points="9 18 15 12 9 6"/></svg>
          </div>
        </div>

        {/* metadata blocks */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginTop:14 }}>
          {[left, right].map((p, i) => (
            <div key={p.id} style={{
              background:'var(--t-quiet-2)', borderRadius:10, padding:'10px 12px',
              boxShadow:'inset 0 0 0 1px var(--t-border)'
            }}>
              <div style={{ fontSize:9.5, letterSpacing:'0.14em', textTransform:'uppercase', color: i === 0 ? 'var(--t-fg-muted)' : '#4FCBE8', marginBottom:6, fontWeight:500 }}>
                {i === 0 ? 'Before' : 'After'}
              </div>
              <div style={{ fontSize:18, fontWeight:500, letterSpacing:'-0.015em', fontVariantNumeric:'tabular-nums', lineHeight:1.1 }}>Day {p.day}</div>
              <div style={{ fontSize:11.5, color:'var(--t-fg-3)', marginTop:4, fontVariantNumeric:'tabular-nums' }}>
                Tray {p.tray} · {p.date}
              </div>
            </div>
          ))}
        </div>
      </Card>

      <Card padding={14}>
        <Rail value={left.id}  onChange={(id) => onPick({ left: id })}  label="Before"/>
        <div style={{ height:10 }}/>
        <Rail value={right.id} onChange={(id) => onPick({ right: id })} label="After"/>
      </Card>
    </div>
  );
}

// ──────────────────────────────────────────────
// Timeline — large hero photo + horizontal scrubber across all captures
// ──────────────────────────────────────────────
function TimelineView({ photos, onCompare }) {
  const [idx, setIdx] = useStateP(photos.length - 1);
  const p = photos[idx];
  const trackRef = useRefP(null);
  const dragging = useRefP(false);

  // map index → percent across timeline based on the photo's day, so spacing reflects real treatment
  const minDay = photos[0].day;
  const maxDay = photos[photos.length - 1].day;
  const dayPct = (d) => (d - minDay) / (maxDay - minDay) * 100;

  const setByX = (clientX) => {
    const el = trackRef.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const x = Math.max(0, Math.min(r.width, clientX - r.left));
    const pct = x / r.width;
    // pick the photo with nearest dayPct
    let best = 0, bestDist = Infinity;
    photos.forEach((ph, i) => {
      const d = Math.abs(dayPct(ph.day) - pct * 100);
      if (d < bestDist) { bestDist = d; best = i; }
    });
    setIdx(best);
  };
  useEffectP(() => {
    const onMove = (e) => {
      if (!dragging.current) return;
      const cx = e.touches ? e.touches[0].clientX : e.clientX;
      setByX(cx);
    };
    const onUp = () => { dragging.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchmove', onMove, { passive: false });
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('touchend', onUp);
    };
  }, []);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <Card padding={14}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10 }}>
          <Eyebrow>Scrub your smile</Eyebrow>
          <span style={{ fontSize:11, color:'var(--t-fg-muted)', fontVariantNumeric:'tabular-nums' }}>{idx + 1} of {photos.length}</span>
        </div>

        {/* Hero photo */}
        <div style={{ position:'relative', width:'100%', aspectRatio:'4/5', borderRadius:12, overflow:'hidden' }}>
          <SmilePhoto day={p.day} tray={p.tray} t={p.day / PLAN_TOTAL_DAYS} rounded={12} showCaption={false}/>
          <div style={{ position:'absolute', top:10, left:10, display:'flex', gap:6 }}>
            <PhotoTag bg="rgba(0,0,0,0.55)" color="#fff">DAY {p.day}</PhotoTag>
            <PhotoTag bg="rgba(0,0,0,0.55)" color="#fff">TRAY {p.tray}</PhotoTag>
          </div>
          {p.tag && (
            <div style={{ position:'absolute', top:10, right:10 }}>
              <PhotoTag bg="rgba(31,184,224,0.78)" color="#fff">{p.tag.toUpperCase()}</PhotoTag>
            </div>
          )}
          <div style={{ position:'absolute', left:0, right:0, bottom:0, padding:'18px 14px 12px', background:'linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.55) 100%)' }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', color:'#fff' }}>
              <div>
                <div style={{ fontSize:11, fontFamily:'Geist Mono, monospace', letterSpacing:'0.06em', opacity:0.8 }}>CAPTURED</div>
                <div style={{ fontSize:14, fontWeight:500, marginTop:2, letterSpacing:'-0.005em' }}>{p.full}</div>
              </div>
              <div style={{ fontSize:11, fontFamily:'Geist Mono, monospace', opacity:0.85 }}>{Math.round(p.day / PLAN_TOTAL_DAYS * 100)}%</div>
            </div>
          </div>
        </div>

        {/* Scrubber */}
        <div ref={trackRef}
          onMouseDown={(e) => { dragging.current = true; setByX(e.clientX); }}
          onTouchStart={(e) => { dragging.current = true; setByX(e.touches[0].clientX); }}
          style={{
            position:'relative', height:64, marginTop:14, padding:'14px 0',
            touchAction:'none', userSelect:'none', cursor:'grab'
          }}>
          {/* baseline track */}
          <div style={{ position:'absolute', left:0, right:0, top:'50%', height:2, transform:'translateY(-50%)', background:'var(--t-quiet-3)', borderRadius:1 }}/>
          {/* progress fill */}
          <div style={{
            position:'absolute', left:0, top:'50%', height:2, transform:'translateY(-50%)',
            width: `${dayPct(p.day)}%`,
            background:'linear-gradient(90deg,#1FB8E0,#3CBF9E)', borderRadius:1
          }}/>
          {/* tick marks */}
          {photos.map((ph, i) => {
            const sel = i === idx;
            return (
              <div key={ph.id} style={{
                position:'absolute', top:'50%', left:`${dayPct(ph.day)}%`,
                transform:'translate(-50%,-50%)',
                width: sel ? 16 : 8, height: sel ? 16 : 8, borderRadius:'50%',
                background: sel ? '#FFFFFF' : ph.tag ? '#3CBF9E' : 'var(--t-fg-muted)',
                boxShadow: sel ? '0 0 0 4px rgba(31,184,224,0.25), 0 2px 6px rgba(0,0,0,0.3)' : 'none',
                transition:'width 160ms, height 160ms'
              }}/>
            );
          })}
        </div>

        {/* day labels */}
        <div style={{ display:'flex', justifyContent:'space-between', fontSize:10, color:'var(--t-fg-muted)', fontVariantNumeric:'tabular-nums', letterSpacing:'0.04em', marginTop:-4 }}>
          <span>Day {minDay}</span>
          <span>Day {Math.round((minDay+maxDay)/2)}</span>
          <span>Day {maxDay}</span>
        </div>

        {/* nav buttons */}
        <div style={{ display:'flex', gap:8, marginTop:14 }}>
          <button onClick={() => setIdx(Math.max(0, idx-1))} style={{
            flex:1, padding:'12px 0', background:'var(--t-quiet-2)', color:'var(--t-fg-1)', border:0,
            borderRadius:10, fontFamily:'inherit', fontSize:13, fontWeight:500, cursor:'pointer',
            boxShadow:'inset 0 0 0 1px var(--t-border)', display:'flex', alignItems:'center', justifyContent:'center', gap:6
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"><polyline points="15 18 9 12 15 6"/></svg>
            Previous
          </button>
          <button onClick={() => setIdx(Math.min(photos.length-1, idx+1))} style={{
            flex:1, padding:'12px 0', background:'var(--t-quiet-2)', color:'var(--t-fg-1)', border:0,
            borderRadius:10, fontFamily:'inherit', fontSize:13, fontWeight:500, cursor:'pointer',
            boxShadow:'inset 0 0 0 1px var(--t-border)', display:'flex', alignItems:'center', justifyContent:'center', gap:6
          }}>
            Next
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"><polyline points="9 18 15 12 9 6"/></svg>
          </button>
        </div>
      </Card>

      <Card padding={14}>
        <div style={{ display:'flex', alignItems:'flex-start', gap:12 }}>
          <div style={{ width:32, height:32, borderRadius:10, background:'rgba(31,184,224,0.12)', display:'flex', alignItems:'center', justifyContent:'center', flex:'none' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#4FCBE8" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
          </div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:13, fontWeight:500, marginBottom:4 }}>Want a side-by-side?</div>
            <div style={{ fontSize:12, color:'var(--t-fg-3)', lineHeight:1.5 }}>Compare this capture against any earlier photo to see the change clearly.</div>
            <button onClick={() => onCompare(PROGRESS_PHOTOS[0].id, p.id)} style={{
              marginTop:10, background:'var(--t-quiet)', color:'var(--t-fg-1)', border:0,
              padding:'8px 12px', borderRadius:10, fontFamily:'inherit', fontSize:12, fontWeight:500, cursor:'pointer'
            }}>Open compare ›</button>
          </div>
        </div>
      </Card>
    </div>
  );
}

// ──────────────────────────────────────────────
// Capture sheet — viewfinder mock with live auto-tag chips
// ──────────────────────────────────────────────
function CaptureSheet({ onClose, onSave }) {
  const [stage, setStage] = useStateP('frame'); // frame → captured
  const today = { day: 84, tray: 14, date: 'May 7', time: '9:41 AM' };

  return (
    <div style={{
      position:'absolute', inset:0, zIndex:80, background:'#0A0C10',
      display:'flex', flexDirection:'column'
    }}>
      {/* viewfinder */}
      <div style={{ position:'relative', flex:1, overflow:'hidden' }}>
        <div style={{ position:'absolute', inset:0 }}>
          <SmilePhoto day={today.day} tray={today.tray} t={1} rounded={0} showCaption={false}/>
        </div>

        {/* top bar */}
        <div style={{ position:'absolute', top:0, left:0, right:0, padding:'56px 18px 0', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <button onClick={onClose} style={{ background:'rgba(0,0,0,0.45)', backdropFilter:'blur(8px)', WebkitBackdropFilter:'blur(8px)', color:'#fff', border:0, width:34, height:34, borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
          <div style={{ fontSize:12, color:'#fff', fontFamily:'Geist Mono, monospace', letterSpacing:'0.06em', background:'rgba(0,0,0,0.45)', padding:'6px 10px', borderRadius:999, backdropFilter:'blur(8px)' }}>
            FRONT · OPEN SMILE
          </div>
          <div style={{ width:34 }}/>
        </div>

        {/* alignment guide — simple smile arc */}
        <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', pointerEvents:'none' }}>
          <svg width="78%" height="42%" viewBox="0 0 200 120" fill="none">
            <path d="M20 30 Q100 110 180 30" stroke="rgba(255,255,255,0.55)" strokeWidth="1.5" strokeDasharray="4 6"/>
            <path d="M20 30 L20 50 M180 30 L180 50" stroke="rgba(255,255,255,0.55)" strokeWidth="1.5"/>
          </svg>
        </div>

        {/* auto-tag chips */}
        <div style={{ position:'absolute', bottom:130, left:0, right:0, display:'flex', flexWrap:'wrap', gap:6, justifyContent:'center', padding:'0 22px' }}>
          <PhotoTag bg="rgba(31,184,224,0.78)" color="#fff">
            <span style={{ display:'inline-block', width:5, height:5, borderRadius:'50%', background:'#fff' }}/>
            AUTO · TRAY {today.tray}
          </PhotoTag>
          <PhotoTag bg="rgba(60,191,158,0.78)" color="#fff">
            <span style={{ display:'inline-block', width:5, height:5, borderRadius:'50%', background:'#fff' }}/>
            DAY {today.day}
          </PhotoTag>
          <PhotoTag bg="rgba(0,0,0,0.55)" color="#fff">{today.date} · {today.time}</PhotoTag>
        </div>

        {/* shutter */}
        {stage === 'frame' && (
          <div style={{ position:'absolute', bottom:36, left:0, right:0, display:'flex', alignItems:'center', justifyContent:'center', gap:38 }}>
            <button onClick={onClose} style={{ width:42, height:42, borderRadius:'50%', background:'rgba(255,255,255,0.10)', backdropFilter:'blur(10px)', WebkitBackdropFilter:'blur(10px)', border:0, color:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
            </button>
            <button onClick={() => setStage('captured')} aria-label="Capture" style={{
              width:76, height:76, borderRadius:'50%', background:'#FFFFFF', border:'4px solid rgba(255,255,255,0.35)',
              boxShadow:'0 8px 28px rgba(0,0,0,0.45)', cursor:'pointer'
            }}/>
            <button style={{ width:42, height:42, borderRadius:'50%', background:'rgba(255,255,255,0.10)', backdropFilter:'blur(10px)', WebkitBackdropFilter:'blur(10px)', border:0, color:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M23 4v6h-6"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
            </button>
          </div>
        )}
      </div>

      {/* review tray */}
      {stage === 'captured' && (
        <div style={{ background:'#0E1014', padding:'18px 22px 28px', borderTop:'1px solid rgba(255,255,255,0.06)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:14, marginBottom:14 }}>
            <div style={{ width:70, height:90, borderRadius:8, overflow:'hidden', flex:'none' }}>
              <SmilePhoto day={today.day} tray={today.tray} t={1} rounded={8} showCaption={false}/>
            </div>
            <div style={{ flex:1, minWidth:0 }}>
              <Eyebrow style={{ marginBottom:6 }}>Saved with</Eyebrow>
              <div style={{ display:'flex', flexWrap:'wrap', gap:4 }}>
                <PhotoTag bg="rgba(31,184,224,0.18)" color="#4FCBE8">TRAY {today.tray}</PhotoTag>
                <PhotoTag bg="rgba(60,191,158,0.18)" color="#5FCFB2">DAY {today.day}</PhotoTag>
                <PhotoTag bg="rgba(255,255,255,0.06)" color="rgba(255,255,255,0.75)">{today.date} · {today.time}</PhotoTag>
              </div>
              <div style={{ fontSize:11, color:'var(--t-fg-muted)', marginTop:8, lineHeight:1.5 }}>
                Tags pulled from your treatment plan. You can edit them anytime.
              </div>
            </div>
          </div>
          <div style={{ display:'flex', gap:8 }}>
            <Btn variant="quiet" block onClick={() => setStage('frame')}>Retake</Btn>
            <Btn variant="primary" block onClick={onSave}>Add to progress</Btn>
          </div>
        </div>
      )}
    </div>
  );
}

// ──────────────────────────────────────────────
// Main screen
// ──────────────────────────────────────────────
function ScreenProgress({ go }) {
  const [mode, setMode] = useStateP('gallery'); // gallery | compare | timeline
  const [capturing, setCapturing] = useStateP(false);
  const [compareIds, setCompareIds] = useStateP({
    left: PROGRESS_PHOTOS[0].id,
    right: PROGRESS_PHOTOS[PROGRESS_PHOTOS.length-1].id
  });

  const openCompare = (leftId, rightId) => {
    setCompareIds({ left: leftId, right: rightId });
    setMode('compare');
  };

  return (
    <div className="pp-screen" style={{ height:'100%', display:'flex', flexDirection:'column', overflowY:'auto' }}>
      <div style={{
        position:'sticky', top:0, zIndex:5, padding:'56px 22px 14px',
        background:'var(--t-sticky-grad)',
        backdropFilter:'blur(12px)', WebkitBackdropFilter:'blur(12px)'
      }}>
        <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between' }}>
          <div>
            <Eyebrow>Progress</Eyebrow>
            <div style={{ fontSize:22, fontWeight:500, letterSpacing:'-0.02em', marginTop:4 }}>Your smile, over time</div>
          </div>
          <button onClick={() => setCapturing(true)} aria-label="Capture"
            style={{ width:38, height:38, borderRadius:'50%', background:'linear-gradient(135deg,#1FB8E0,#3CBF9E)', color:'#fff', border:0, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 6px 18px rgba(31,184,224,0.35)' }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
          </button>
        </div>

        {/* mode toggle */}
        <div style={{ marginTop:14, display:'flex', gap:4, padding:3, background:'var(--t-quiet-2)', borderRadius:10 }}>
          {[['gallery','Gallery'],['compare','Compare'],['timeline','Timeline']].map(([v,l]) => (
            <button key={v} onClick={() => setMode(v)}
              style={{
                flex:1, padding:'8px 0', border:0, borderRadius:7, cursor:'pointer',
                background: mode === v ? 'var(--t-pill-active-bg)' : 'transparent',
                color: mode === v ? 'var(--t-pill-active-fg)' : 'var(--t-fg-3)',
                fontFamily:'inherit', fontSize:12, fontWeight:500, transition:'all 160ms'
              }}>{l}</button>
          ))}
        </div>
      </div>

      <div style={{ padding:'4px 22px 110px' }}>
        {mode === 'gallery' && (
          <GalleryView
            photos={PROGRESS_PHOTOS}
            onOpen={(id) => openCompare(PROGRESS_PHOTOS[0].id, id)}
            onCompare={openCompare}
            onCapture={() => setCapturing(true)}
          />
        )}
        {mode === 'compare' && (
          <CompareView
            photos={PROGRESS_PHOTOS}
            leftId={compareIds.left}
            rightId={compareIds.right}
            onPick={(p) => setCompareIds(prev => ({ ...prev, ...p }))}
          />
        )}
        {mode === 'timeline' && (
          <TimelineView photos={PROGRESS_PHOTOS} onCompare={openCompare}/>
        )}
      </div>

      <TabBar active="progress" go={go}/>

      {capturing && <CaptureSheet onClose={() => setCapturing(false)} onSave={() => setCapturing(false)}/>}
    </div>
  );
}

Object.assign(window, { ScreenProgress, PROGRESS_PHOTOS, SmilePhoto, PhotoTag });
