// screenshot.jsx — Screenshot import flow for CheekPouch
// Three internal screens:
//   1. ScreenshotSourceSheet  — bottom sheet picker (rendered inside InputScreen)
//   2. ScreenshotDetect       — dark photo-viewer with OCR overlays
//   3. ScreenshotConfirm      — review the cards that will be created

// ─────────────────────────────────────────────────────────────
// Sample OCR regions for the demo screenshot
// (x, y, w, h are fractions of the image's natural size)
// ─────────────────────────────────────────────────────────────
const SS = window.__cpMakeTheme();

const SCREENSHOT_PATH = 'assets/sample-screenshot.png';

const SAMPLE_REGIONS = [
  { id: 'r1', y: 0.135, x: 0.08, w: 0.86, h: 0.072,
    text: '하나님께서 늘 사랑을 주신 것처럼 주는 사랑이 받는 사랑보다 더 복이 있습니다.' },
  { id: 'r2', y: 0.221, x: 0.08, w: 0.86, h: 0.070,
    text: '하나님께 영광을 돌리면 그 영광은 결국 자신의 것이 됩니다.' },
  { id: 'r3', y: 0.305, x: 0.08, w: 0.86, h: 0.070,
    text: '아름답게 보는 마음은 미움이 없고 온전한 사랑을 이루게 합니다.' },
  { id: 'r4', y: 0.387, x: 0.08, w: 0.86, h: 0.138,
    text: '아브라함이 조카 롯에게 좋은 것을 양보했을 때 더 좋은 것으로 축복을 받았듯이 우리들도 형제들에게 좋은 것을 양보하면 더 좋은 축복을 받게 됩니다.' },
  { id: 'r5', y: 0.540, x: 0.08, w: 0.78, h: 0.038,
    text: '높은 마음이란 섭섭하게 느끼는 마음입니다.' },
  { id: 'r6', y: 0.594, x: 0.08, w: 0.86, h: 0.102,
    text: '다른 사람들이 일하지 않는다고 불평하지 말고 자신의 할 일에만 충성되게 합시다.' },
  { id: 'r7', y: 0.710, x: 0.08, w: 0.86, h: 0.102,
    text: '불만이 가득 차면 교만이 생깁니다. 늘 감사하는 마음으로 하나님을 섬기면 겸손한 마음을 갖게 됩니다.' },
  { id: 'r8', y: 0.823, x: 0.08, w: 0.86, h: 0.038,
    text: '형제 자매에게 칭찬하면 내게 칭찬이 돌아옵니다.' },
];

// ─────────────────────────────────────────────────────────────
// STEP 1 — Source sheet (rendered inside InputScreen)
// ─────────────────────────────────────────────────────────────
function ScreenshotSourceSheet({ accent, onClose, onPick }) {
  // Recent screenshots — first is the real demo image, rest are abstract placeholders
  const recent = [
    { id: 'real',  kind: 'real', src: SCREENSHOT_PATH, label: '방금 전' },
    { id: 'p1',    kind: 'placeholder', tone: 'msg',    label: '오늘 11:24' },
    { id: 'p2',    kind: 'placeholder', tone: 'menu',   label: '오늘 09:48' },
    { id: 'p3',    kind: 'placeholder', tone: 'browser',label: '어제' },
    { id: 'p4',    kind: 'placeholder', tone: 'note',   label: '어제' },
    { id: 'p5',    kind: 'placeholder', tone: 'msg2',   label: '4월 22일' },
  ];

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 200,
      display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
    }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'rgba(31, 24, 18, 0.40)',
        animation: 'cp-fade-bg 0.25s ease',
      }} />

      <div style={{
        position: 'relative',
        background: SS.surface,
        borderTopLeftRadius: 26, borderTopRightRadius: 26,
        paddingBottom: 28,
        maxHeight: '88%',
        display: 'flex', flexDirection: 'column',
        boxShadow: '0 -8px 32px rgba(31,24,18,0.16)',
        animation: 'cp-sheet-up 0.34s cubic-bezier(0.22, 1, 0.36, 1)',
      }}>
        <div style={{
          width: 38, height: 4.5, borderRadius: 4,
          background: 'rgba(31,24,18,0.18)',
          margin: '8px auto 14px',
        }} />

        <div style={{ padding: '0 24px 6px' }}>
          <div style={{
            fontSize: 19, fontWeight: 700, letterSpacing: '-0.02em',
            color: SS.ink, lineHeight: 1.2,
          }}>스크린샷에서 담기</div>
          <div style={{
            marginTop: 6,
            fontSize: 13, color: SS.ink2, letterSpacing: '-0.01em',
            lineHeight: 1.5,
          }}>한국어 글이 보이는 이미지면 돼요. 글자를 알아서 찾아드릴게요.</div>
        </div>

        <div style={{ overflowY: 'auto', paddingBottom: 8 }}>
          {/* Recent screenshots grid */}
          <div style={{ padding: '18px 24px 4px',
            fontSize: 11, fontWeight: 600, color: SS.ink3,
            letterSpacing: '0.08em', textTransform: 'uppercase',
          }}>최근 스크린샷</div>

          <div style={{
            padding: '8px 24px 4px',
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: 10,
          }}>
            {recent.map(item => (
              <button key={item.id}
                onClick={() => onPick(item)}
                style={{
                  position: 'relative',
                  aspectRatio: '9 / 16',
                  borderRadius: 12,
                  border: item.kind === 'real' ? `2px solid ${accent}` : `0.5px solid rgba(60,42,20,0.16)`,
                  padding: 0, overflow: 'hidden',
                  background: '#FFF',
                  cursor: 'pointer',
                  WebkitTapHighlightColor: 'transparent',
                  fontFamily: 'inherit',
                }}>
                {item.kind === 'real' ? (
                  <img src={item.src} alt=""
                       style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                ) : (
                  <PlaceholderShot tone={item.tone} />
                )}

                {item.kind === 'real' && (
                  <div style={{
                    position: 'absolute', top: 6, left: 6,
                    height: 18, padding: '0 7px',
                    background: accent, color: '#FFF',
                    borderRadius: 999,
                    fontSize: 9.5, fontWeight: 700, letterSpacing: '0.04em',
                    display: 'inline-flex', alignItems: 'center', gap: 3,
                  }}>
                    <SparkleBlip />
                    텍스트 감지
                  </div>
                )}

                <div style={{
                  position: 'absolute', bottom: 0, left: 0, right: 0,
                  padding: '14px 7px 5px 7px',
                  background: 'linear-gradient(to top, rgba(0,0,0,0.55), transparent)',
                  color: '#FFF',
                  fontSize: 10, fontWeight: 500, letterSpacing: '-0.01em',
                  textAlign: 'left',
                }}>{item.label}</div>
              </button>
            ))}
          </div>

          {/* Or pick from elsewhere */}
          <div style={{
            padding: '20px 24px 4px',
            fontSize: 11, fontWeight: 600, color: SS.ink3,
            letterSpacing: '0.08em', textTransform: 'uppercase',
          }}>다른 곳에서</div>

          <div style={{ padding: '8px 16px 0', display: 'flex', flexDirection: 'column', gap: 4 }}>
            <SourceRow icon={<LibraryGlyph />} title="사진 보관함에서 선택"
                       desc="여러 장을 한꺼번에 고를 수도 있어요" />
            <SourceRow icon={<CameraGlyph />}  title="카메라로 찍기"
                       desc="책, 메뉴판, 안내문 등" />
            <SourceRow icon={<ClipboardGlyph />} title="클립보드에서 붙여넣기"
                       desc="복사해둔 이미지가 있을 때" muted />
          </div>
        </div>
      </div>
    </div>
  );
}

function SourceRow({ icon, title, desc, muted }) {
  return (
    <button style={{
      width: '100%', display: 'flex', alignItems: 'center', gap: 14,
      padding: '12px 12px',
      borderRadius: 14,
      border: 'none', background: 'transparent',
      cursor: muted ? 'default' : 'pointer',
      textAlign: 'left',
      fontFamily: 'inherit',
      opacity: muted ? 0.45 : 1,
      WebkitTapHighlightColor: 'transparent',
    }}>
      <span style={{
        width: 40, height: 40, borderRadius: 12,
        background: SS.inkOverlaySoft,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>{icon}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 15, fontWeight: 500, color: SS.ink,
          letterSpacing: '-0.01em',
        }}>{title}</div>
        <div style={{
          marginTop: 2, fontSize: 12, color: SS.ink3,
          letterSpacing: '-0.01em',
        }}>{desc}</div>
      </div>
      <svg width="8" height="14" viewBox="0 0 8 14" fill="none" style={{ flexShrink: 0 }}>
        <path d="M1.5 1.5L6.5 7L1.5 12.5" stroke="#A8997F" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </button>
  );
}

function PlaceholderShot({ tone }) {
  // Stylized abstract "screenshot" thumbnails — generic UI shapes, no brand mimicry
  const palettes = {
    msg:     { bg: '#E8E0D2', stripe: SS.ink4, strong: '#8B6F47' },
    menu:    { bg: '#EFE6D5', stripe: '#C9BFA7', strong: SS.ink2 },
    browser: { bg: '#E2DACA', stripe: '#BBAF96', strong: SS.ink },
    note:    { bg: '#F0E7D6', stripe: '#D0C2A6', strong: '#8B5C7A' },
    msg2:    { bg: '#E5DDCB', stripe: '#C2B59B', strong: '#4A6B4F' },
  }[tone] || { bg: '#EBE3D2', stripe: SS.ink4, strong: '#8B6F47' };

  return (
    <div style={{
      width: '100%', height: '100%',
      background: palettes.bg, position: 'relative',
    }}>
      {/* tiny status bar */}
      <div style={{
        position: 'absolute', top: 4, left: 6, right: 6,
        height: 4, display: 'flex', justifyContent: 'space-between',
      }}>
        <div style={{ width: 14, height: 3, background: palettes.strong, opacity: 0.5, borderRadius: 1 }} />
        <div style={{ width: 10, height: 3, background: palettes.strong, opacity: 0.5, borderRadius: 1 }} />
      </div>
      {/* stripes */}
      <div style={{ position: 'absolute', inset: '18% 10% 14%',
        display: 'flex', flexDirection: 'column', gap: 4 }}>
        {[0.95, 0.7, 0.85, 0.5, 0.92, 0.65, 0.78].map((w, i) => (
          <div key={i} style={{
            height: 4, width: `${w * 100}%`,
            background: i === 0 ? palettes.strong : palettes.stripe,
            opacity: i === 0 ? 0.85 : 0.6,
            borderRadius: 2,
          }} />
        ))}
      </div>
    </div>
  );
}

// Glyphs
function LibraryGlyph() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <rect x="2.5" y="5.5" width="13" height="10" rx="2" stroke="#1F1812" strokeWidth="1.5"/>
      <rect x="5" y="3" width="13" height="10" rx="2" stroke="#1F1812" strokeWidth="1.5" fill="#FBF7F0"/>
      <circle cx="9" cy="7.5" r="1.2" fill="#1F1812"/>
      <path d="M6 11l2.5-2 2.5 2 3.5-3 2.5 2" stroke="#1F1812" strokeWidth="1.3" strokeLinejoin="round"/>
    </svg>
  );
}
function CameraGlyph() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <rect x="2" y="5.5" width="16" height="11" rx="2.5" stroke="#1F1812" strokeWidth="1.5"/>
      <circle cx="10" cy="11.5" r="3.2" stroke="#1F1812" strokeWidth="1.5"/>
      <path d="M7 5.5l1-1.5h4l1 1.5" stroke="#1F1812" strokeWidth="1.5"/>
    </svg>
  );
}
function ClipboardGlyph() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <rect x="4" y="3.5" width="12" height="14" rx="2" stroke="#1F1812" strokeWidth="1.5"/>
      <rect x="7" y="2" width="6" height="3" rx="1" stroke="#1F1812" strokeWidth="1.5" fill="#FBF7F0"/>
      <path d="M7 9h6M7 12h6M7 15h4" stroke="#1F1812" strokeWidth="1.3" strokeLinecap="round"/>
    </svg>
  );
}
function SparkleBlip() {
  return (
    <svg width="8" height="8" viewBox="0 0 8 8" fill="none">
      <path d="M4 0.6L4.6 3.4L7.4 4L4.6 4.6L4 7.4L3.4 4.6L0.6 4L3.4 3.4L4 0.6Z" fill="#FFF"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// STEP 2 — Detect (dark photo viewer with OCR overlays)
// ─────────────────────────────────────────────────────────────
function ScreenshotDetect({ accent, selected, setSelected, onBack, onNext, regions }) {
  const [scanned, setScanned] = React.useState(false);

  // Scanner sweep animation on enter
  React.useEffect(() => {
    const t = setTimeout(() => setScanned(true), 1100);
    return () => clearTimeout(t);
  }, []);

  const toggle = (id) => {
    setSelected(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const all = () => {
    if (selected.size === regions.length) setSelected(new Set());
    else setSelected(new Set(regions.map(r => r.id)));
  };

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: '#171210',
      animation: 'cp-fade-bg 0.22s ease',
    }}>
      {/* Top bar */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0,
        padding: '54px 14px 8px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        zIndex: 3,
      }}>
        <button onClick={onBack} style={{
          background: 'rgba(255,255,255,0.14)',
          border: 'none', color: '#FFF',
          height: 34, padding: '0 12px', borderRadius: 999,
          fontFamily: 'inherit', fontSize: 14, fontWeight: 500,
          cursor: 'pointer', letterSpacing: '-0.01em',
          display: 'inline-flex', alignItems: 'center', gap: 4,
        }}>
          <svg width="14" height="14" viewBox="0 0 22 22" fill="none">
            <path d="M14 4L7 11l7 7" stroke="#FFF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          뒤로
        </button>
        <div style={{
          fontSize: 14, fontWeight: 600, color: '#FFF',
          letterSpacing: '-0.01em', whiteSpace: 'nowrap',
        }}>텍스트 골라 담기</div>
        <button onClick={all} style={{
          background: 'rgba(255,255,255,0.14)',
          border: 'none', color: '#FFF',
          height: 34, padding: '0 14px', borderRadius: 999,
          fontFamily: 'inherit', fontSize: 13, fontWeight: 500,
          cursor: 'pointer', letterSpacing: '-0.01em',
        }}>{selected.size === regions.length ? '전체 해제' : '전체 선택'}</button>
      </div>

      {/* Detection hint banner */}
      <div style={{
        position: 'absolute', top: 100, left: 14, right: 14,
        zIndex: 3,
        padding: '10px 14px',
        background: 'rgba(255,255,255,0.10)',
        borderRadius: 12,
        border: '0.5px solid rgba(255,255,255,0.10)',
        color: 'rgba(255,255,255,0.92)',
        fontSize: 13, letterSpacing: '-0.01em', lineHeight: 1.35,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{
          width: 22, height: 22, borderRadius: 22,
          background: `${accent}40`,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <svg width="13" height="13" viewBox="0 0 16 16" fill="none">
            <path d="M8 1.5L9 6.5L14 7.5L9 8.5L8 13.5L7 8.5L2 7.5L7 6.5L8 1.5Z" fill={accent}/>
          </svg>
        </span>
        <span style={{ flex: 1, minWidth: 0 }}>
          {scanned ? (
            <><strong style={{ fontWeight: 700, color: '#FFF' }}>{regions.length}개의 문장</strong>을 찾았어요 · 담을 것만 눌러주세요</>
          ) : (
            <><span style={{ color: '#FFF', fontWeight: 600 }}>스크린샷을 읽고 있어요…</span> 잠시만요</>
          )}
        </span>
      </div>

      {/* Image with overlays */}
      <div style={{
        position: 'absolute', top: 156, bottom: 96, left: 0, right: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '0 18px',
      }}>
        <div style={{
          position: 'relative',
          width: 314, height: 620,
          maxWidth: '100%',
          borderRadius: 14, overflow: 'hidden',
          boxShadow: '0 12px 40px rgba(0,0,0,0.55)',
          background: '#FBF1DE',
        }}>
          <img src={SCREENSHOT_PATH} alt="" style={{
            position: 'absolute', top: 0, left: 0,
            width: '100%', height: '100%',
            display: 'block',
          }} />

          {/* Scanning sweep */}
          {!scanned && (
            <div style={{
              position: 'absolute', inset: 0,
              pointerEvents: 'none',
              overflow: 'hidden',
            }}>
              <div style={{
                position: 'absolute', left: 0, right: 0, height: 90,
                background: `linear-gradient(to bottom, transparent 0%, ${accent}33 45%, ${accent}99 50%, ${accent}33 55%, transparent 100%)`,
                animation: 'cp-scan 1.1s ease-out forwards',
              }} />
            </div>
          )}

          {/* OCR boxes */}
          {scanned && regions.map((r, i) => {
            const isOn = selected.has(r.id);
            return (
              <button key={r.id} onClick={() => toggle(r.id)} style={{
                position: 'absolute',
                top: `${r.y * 100}%`, left: `${r.x * 100}%`,
                width: `${r.w * 100}%`, height: `${r.h * 100}%`,
                border: isOn ? `2px solid ${accent}` : `1.2px dashed rgba(255,255,255,0.85)`,
                background: isOn ? `${accent}33` : 'rgba(255,255,255,0.04)',
                borderRadius: 5,
                padding: 0, margin: 0,
                cursor: 'pointer',
                WebkitTapHighlightColor: 'transparent',
                transition: 'background 0.18s ease, border-color 0.18s ease',
                animation: `cp-fade-in 0.22s ${i * 0.04}s both`,
              }}>
                {isOn && (
                  <span style={{
                    position: 'absolute', top: -10, right: -10,
                    width: 22, height: 22, borderRadius: 22,
                    background: accent, color: '#FFF',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    border: '2px solid #171210',
                    boxShadow: '0 2px 6px rgba(0,0,0,0.35)',
                  }}>
                    <svg width="10" height="10" viewBox="0 0 14 14" fill="none">
                      <path d="M3 7.2l2.8 2.8L11 5" stroke="#FFF" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </span>
                )}
              </button>
            );
          })}
        </div>
      </div>

      {/* Bottom action bar */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 18px 28px',
        background: 'linear-gradient(to top, #171210 60%, rgba(23,18,16,0.0))',
        display: 'flex', alignItems: 'center', gap: 12,
        zIndex: 3,
      }}>
        <div style={{
          flex: 1, minWidth: 0,
          color: 'rgba(255,255,255,0.96)',
          fontSize: 14, letterSpacing: '-0.01em',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>
          {selected.size === 0 ? (
            <span style={{ color: 'rgba(255,255,255,0.55)' }}>담을 문장을 골라주세요</span>
          ) : (
            <>
              <strong style={{ fontWeight: 700, color: '#FFF' }}>{selected.size}개</strong>
              <span style={{ color: 'rgba(255,255,255,0.55)' }}> · {regions.length}개 중</span>
            </>
          )}
        </div>
        <button onClick={onNext} disabled={selected.size === 0} style={{
          height: 46, padding: '0 22px',
          borderRadius: 999,
          background: selected.size > 0 ? accent : 'rgba(255,255,255,0.16)',
          color: selected.size > 0 ? '#FFF' : 'rgba(255,255,255,0.45)',
          border: 'none',
          fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
          cursor: selected.size > 0 ? 'pointer' : 'default',
          letterSpacing: '-0.01em',
          display: 'inline-flex', alignItems: 'center', gap: 6,
          transition: 'background 0.18s ease',
          WebkitTapHighlightColor: 'transparent',
        }}>
          다음
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M5 3l4 4-4 4" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// STEP 3 — Confirm (review cards before submit)
// ─────────────────────────────────────────────────────────────
function ScreenshotConfirm({ accent, items, setItems, onBack, onSubmit, langSel, setLangSel, tone, setTone, cat, setCat, customCats, addCustomCat }) {
  const [sheetOpen, setSheetOpen] = React.useState(null);

  const remove = (id) => setItems(arr => arr.filter(it => it.id !== id));

  return (
    <div style={{ paddingBottom: 100 }}>
      {/* Top bar */}
      <div style={{
        padding: '54px 22px 6px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={onBack} style={{
          background: 'none', border: 'none', padding: 0,
          fontSize: 16, color: SS.ink2, cursor: 'pointer',
          fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 4,
          letterSpacing: '-0.01em',
        }}>
          <svg width="16" height="16" viewBox="0 0 22 22" fill="none">
            <path d="M14 4L7 11l7 7" stroke="#6B5D4A" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          뒤로
        </button>
        <div style={{
          fontSize: 16, fontWeight: 600, color: SS.ink, letterSpacing: '-0.01em',
          whiteSpace: 'nowrap',
        }}>담을 씨앗 확인</div>
        <button onClick={() => onSubmit(items)} disabled={items.length === 0} style={{
          background: 'none', border: 'none', padding: 0,
          fontSize: 16, fontWeight: 600,
          color: items.length > 0 ? accent : SS.ink4,
          cursor: items.length > 0 ? 'pointer' : 'default',
          fontFamily: 'inherit',
        }}>완료</button>
      </div>

      {/* Headline */}
      <div style={{ padding: '14px 22px 0' }}>
        <div style={{
          fontSize: 26, fontWeight: 700, color: SS.ink,
          letterSpacing: '-0.02em', lineHeight: 1.2,
        }}>
          <span style={{ color: accent }}>{items.length}개</span>의 표현
        </div>
        <div style={{
          marginTop: 6,
          fontSize: 14, color: SS.ink2, letterSpacing: '-0.01em',
          lineHeight: 1.45,
        }}>이대로 담으면 아래 설정으로 씨앗이 만들어져요.<br/>각 씨앗은 눌러서 따로 고칠 수 있어요.</div>
      </div>

      {/* Shared options */}
      <div style={{
        padding: '16px 22px 0',
        display: 'flex', gap: 8, flexWrap: 'wrap',
      }}>
        <Selector label="언어"     value={langSel} onClick={() => setSheetOpen('lang')} />
        <Selector label="톤"       value={tone}    onClick={() => setSheetOpen('tone')} />
        <Selector label="카테고리" value={cat === '자동' ? '자동 분류' : cat}
                  isAuto={cat === '자동'} accent={accent}
                  onClick={() => setSheetOpen('cat')} />
      </div>

      {/* Card preview list */}
      <div style={{ padding: '20px 22px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map((it, i) => (
          <PreviewCard key={it.id} item={it} accent={accent} index={i + 1}
                       onRemove={() => remove(it.id)} />
        ))}

        {items.length === 0 && (
          <div style={{
            padding: '32px 18px',
            border: '1px dashed rgba(60,42,20,0.18)',
            borderRadius: 16,
            textAlign: 'center',
            color: SS.ink3, fontSize: 14, letterSpacing: '-0.01em',
          }}>모든 씨앗을 삭제했어요. 뒤로 가서 다시 골라주세요.</div>
        )}
      </div>

      {/* Footer disclaimer */}
      <div style={{
        margin: '24px 22px 0',
        padding: '14px 16px',
        background: SS.surface,
        border: '0.5px solid rgba(60,42,20,0.09)',
        borderRadius: 14,
        fontSize: 12, color: SS.ink2, lineHeight: 1.5,
        letterSpacing: '-0.01em',
      }}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ marginTop: 2, flexShrink: 0 }}>
            <circle cx="7" cy="7" r="6" stroke="#A8997F" strokeWidth="1.3"/>
            <path d="M7 4.5v3M7 9.5h.01" stroke="#A8997F" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
          <div>
            번역과 발음은 완료 후 씨앗별로 자동 생성됩니다.<br/>
            씨앗을 만든 뒤에도 편집 화면에서 다시 다듬을 수 있어요.
          </div>
        </div>
      </div>

      {/* Picker sheets reuse global versions */}
      {sheetOpen === 'lang' && (
        <PickerSheet
          title="어느 나라 말로 담을까요?"
          options={LANG_OPTIONS.map(o => ({ value: o.value, label: o.value, prefix: o.flag }))}
          current={langSel} accent={accent}
          onSelect={(v) => { setLangSel(v); setSheetOpen(null); }}
          onClose={() => setSheetOpen(null)}
        />
      )}
      {sheetOpen === 'tone' && (
        <PickerSheet
          title="어떤 톤으로 만들까요?"
          options={TONE_OPTIONS.map(o => ({ value: o.value, label: o.value, desc: o.desc }))}
          current={tone} accent={accent}
          onSelect={(v) => { setTone(v); setSheetOpen(null); }}
          onClose={() => setSheetOpen(null)}
        />
      )}
      {sheetOpen === 'cat' && (
        <CategorySheet
          current={cat}
          baseCats={BASE_CATS}
          customCats={customCats}
          accent={accent}
          onSelect={(v) => { setCat(v); setSheetOpen(null); }}
          onAddCustom={(v) => { addCustomCat(v); setCat(v); setSheetOpen(null); }}
          onClose={() => setSheetOpen(null)}
        />
      )}
    </div>
  );
}

function PreviewCard({ item, accent, index, onRemove }) {
  return (
    <div style={{
      background: SS.surface,
      border: '0.5px solid rgba(60,42,20,0.09)',
      borderRadius: 16,
      padding: '14px 16px',
      display: 'flex', alignItems: 'flex-start', gap: 12,
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 22, flexShrink: 0,
        background: `${accent}1A`,
        color: accent,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 11, fontWeight: 700, fontFamily: 'ui-monospace, SFMono-Regular, monospace',
      }}>{index}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 15, color: SS.ink, letterSpacing: '-0.01em',
          lineHeight: 1.45,
        }}>{item.text}</div>
        <div style={{
          marginTop: 10, display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 11, color: SS.ink3, letterSpacing: '0.02em',
        }}>
          <span style={{
            height: 18, padding: '0 7px',
            background: SS.inkOverlaySoft,
            color: SS.ink2,
            borderRadius: 4,
            display: 'inline-flex', alignItems: 'center',
            fontWeight: 500, whiteSpace: 'nowrap',
          }}>
            <SparkleBlipDark color={accent} />
            <span style={{ marginLeft: 4 }}>번역 자동 생성</span>
          </span>
        </div>
      </div>
      <button onClick={onRemove} style={{
        width: 28, height: 28, borderRadius: 28,
        background: 'transparent',
        border: '0.5px solid rgba(60,42,20,0.16)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', flexShrink: 0,
        WebkitTapHighlightColor: 'transparent',
      }}>
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
          <path d="M2 2l6 6M8 2l-6 6" stroke="#6B5D4A" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
      </button>
    </div>
  );
}

function SparkleBlipDark({ color }) {
  return (
    <svg width="8" height="8" viewBox="0 0 8 8" fill="none">
      <path d="M4 0.6L4.6 3.4L7.4 4L4.6 4.6L4 7.4L3.4 4.6L0.6 4L3.4 3.4L4 0.6Z" fill={color}/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Top-level wrapper used by app.jsx
// ─────────────────────────────────────────────────────────────
function ScreenshotFlow({ accent, initialItems, onBack, onSubmit, customCats, addCustomCat }) {
  // Single screen — confirm step. Detect step is rendered separately as 'detectScreenshot'.
  // (kept for symmetry; not currently used directly)
  return null;
}

// Expose to global scope so app.jsx can use them
Object.assign(window, {
  ScreenshotSourceSheet,
  ScreenshotDetect,
  ScreenshotConfirm,
  SAMPLE_REGIONS,
  SCREENSHOT_PATH,
});
