import React from 'react';
import { View, Text, StyleSheet, LayoutChangeEvent } from 'react-native';
import { PREVIEW_SIZE } from './format';

/**
 * 渐变预览承载盒:固定 200×200 的白底带框区域 + 可选的下方刻度尺。
 *
 * 刻度尺画在盒**外面**,不叠加在渐变上——叠加会引入额外颜色,
 * 而本库多条判据是「画面中不出现红色/蓝色」这类色相判断,压线的辅助线会污染判读。
 * 刻度标到 40 / 100 vp,正好对应判据里反复出现的「盒边长五分之一」「二分之一」。
 */

interface PreviewBoxProps {
  onBoxLayout: (e: LayoutChangeEvent) => void;
  showRuler?: boolean;
  children: React.ReactNode;
}

export function PreviewBox({ onBoxLayout, showRuler, children }: PreviewBoxProps) {
  return (
    <View style={styles.wrap}>
      <View testID="view_preview_frame" style={styles.frame} onLayout={onBoxLayout}>
        {children}
      </View>
      {showRuler ? (
        <View style={styles.ruler}>
          <View style={styles.rulerBar} />
          {[
            { at: 0, text: '0' },
            { at: 40, text: '40' },
            { at: 100, text: '100' },
            { at: 200, text: '200' },
          ].map((t) => (
            <View
              key={t.text}
              style={[styles.tick, { left: (t.at / PREVIEW_SIZE) * PREVIEW_SIZE - 12 }]}>
              <View style={styles.tickMark} />
              <Text style={styles.tickText}>{t.text}</Text>
            </View>
          ))}
          <Text style={styles.rulerUnit}>vp(横向标尺,1/5 = 40,1/2 = 100)</Text>
        </View>
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: { marginTop: 6, marginBottom: 8, alignItems: 'center' },
  frame: {
    width: PREVIEW_SIZE,
    height: PREVIEW_SIZE,
    borderWidth: 1,
    borderColor: '#ddd',
    backgroundColor: '#fff',
  },
  ruler: { width: PREVIEW_SIZE, height: 34, marginTop: 2 },
  rulerBar: { position: 'absolute', top: 0, left: 0, right: 0, height: 1, backgroundColor: '#bbb' },
  tick: { position: 'absolute', top: 0, width: 24, alignItems: 'center' },
  tickMark: { width: 1, height: 5, backgroundColor: '#bbb' },
  tickText: { fontSize: 9, color: '#777' },
  rulerUnit: { position: 'absolute', top: 20, left: 0, fontSize: 9, color: '#999' },
});