// Screen 5: Share card (the screenshot deliverable)
function ShareCard({ result, size = 'tall', qrDataUrl }) {
  // size 'tall' = 1080x1920, 'square' = 1080x1350
  const { code, scores } = result;
  const type = TYPES[code];
  const isLight = code !== 'ERSP'; // 只有 ERSP（高压锻造厂）是深色背景
  const fg = isLight ? '#2A1F14' : '#FFF8EE';
  const sub = isLight ? 'rgba(42,31,20,0.6)' : 'rgba(255,248,238,0.7)';

  // Render at small scale for in-frame preview but with proportions of real card
  const aspect = size === 'tall' ? 1080 / 1920 : 1080 / 1350;

  return (
    <div style={{
      width: '100%', aspectRatio: `${aspect}`,
      borderRadius: 16, overflow: 'hidden', position: 'relative',
      background: type.bg, color: fg,
      boxShadow: '0 16px 40px rgba(0,0,0,0.2)',
      display: 'flex', flexDirection: 'column',
      padding: '6.5% 7%',
    }}>
      {/* Decorative background */}
      <div style={{
        position: 'absolute', top: '-15%', right: '-25%', width: '70%', aspectRatio: '1',
        borderRadius: '50%', background: type.accent + '40',
      }} />
      <div style={{
        position: 'absolute', bottom: '-15%', left: '-20%', width: '60%', aspectRatio: '1',
        borderRadius: '50%', background: type.accent + '22',
      }} />

      {/* Header label */}
      <div style={{
        fontFamily: 'var(--font-body)', fontSize: '2.6cqw', letterSpacing: '0.6em',
        fontWeight: 500, opacity: 0.55, position: 'relative', zIndex: 1,
        marginBottom: '2%',
      }}>FAMILY · MBTI</div>

      <div style={{
        fontFamily: 'var(--font-display)', fontSize: '4cqw', fontWeight: 600,
        opacity: 0.7, position: 'relative', zIndex: 1, marginBottom: '4%',
      }}>我家是 —</div>

      {/* Main: emoji + name */}
      <div style={{ position: 'relative', zIndex: 1, marginBottom: '4%' }}>
        <div style={{ fontSize: '20cqw', lineHeight: 1, marginBottom: '2%',
          filter: `drop-shadow(0 6px 30px ${type.accent})`,
        }}>{type.emoji}</div>
        <div style={{
          fontFamily: 'var(--font-display)', fontSize: '11cqw', fontWeight: 800,
          lineHeight: 1, letterSpacing: '-0.02em', marginBottom: '1.5%',
        }}>{type.name}</div>
        <div style={{
          fontFamily: 'var(--font-body)', fontSize: '4cqw', lineHeight: 1.4,
          fontStyle: 'italic', opacity: 0.85,
        }}>"{type.oneline}"</div>
      </div>

      {/* 4-letter blocks — dynamic */}
      <div style={{ position: 'relative', zIndex: 1, display: 'flex', gap: '1.8cqw', marginBottom: '5%' }}>
        {code.split('').map((letter, i) => {
          const dim = DIMS[['DE','RA','SO','PM'][i]];
          return (
            <div key={i} style={{
              width: '14cqw', height: '17cqw', borderRadius: '2.5cqw',
              background: dim.color, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: '9cqw',
              boxShadow: `0 1cqw 3cqw ${dim.color}99`,
              transform: `rotate(${[-3,1.5,-1.5,3][i]}deg)`,
            }}>{letter}</div>
          );
        })}
      </div>

      {/* Dimension bars in card */}
      <div style={{
        position: 'relative', zIndex: 1,
        background: isLight ? 'rgba(255,255,255,0.55)' : 'rgba(255,255,255,0.1)',
        backdropFilter: 'blur(8px)',
        borderRadius: '3cqw', padding: '4cqw',
        display: 'flex', flexDirection: 'column', gap: '2.5cqw',
        marginBottom: 'auto',
      }}>
        {['DE','RA','SO','PM'].map(k => {
          const d = DIMS[k];
          const score = scores[k];
          const right = score >= 2;
          const pct = (score / 3) * 100;
          return (
            <div key={k}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.8cqw', gap: '1cqw' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '1cqw', fontSize: '2.6cqw', fontWeight: 600, whiteSpace: 'nowrap' }}>
                  <span style={{ fontSize: '3cqw' }}>{d.emoji}</span>
                  <span>{d.name}</span>
                </div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: '2.8cqw', color: d.color, whiteSpace: 'nowrap' }}>
                  {right ? d.rightLabel : d.leftLabel}
                </div>
              </div>
              <div style={{
                position: 'relative', height: '1.4cqw', borderRadius: '0.7cqw',
                background: isLight ? '#00000018' : '#FFFFFF22', overflow: 'hidden',
              }}>
                <div style={{
                  position: 'absolute', top: 0, bottom: 0,
                  left: right ? '50%' : `${50 - pct/2}%`,
                  width: `${pct/2}%`,
                  background: d.color,
                }} />
                <div style={{ position: 'absolute', top: 0, bottom: 0, left: '50%', width: 1, background: isLight ? '#00000022' : '#FFFFFF44' }} />
              </div>
            </div>
          );
        })}
      </div>

      {/* Footer */}
      <div style={{
        position: 'relative', zIndex: 1, display: 'flex',
        alignItems: 'center', justifyContent: 'space-between',
        marginTop: '4%',
      }}>
        <div>
          <div style={{ fontSize: '2.6cqw', color: sub, fontFamily: 'var(--font-body)', marginBottom: '0.6cqw' }}>扫码测你家的 →</div>
          <div style={{ fontSize: '3.2cqw', fontFamily: 'var(--font-display)', fontWeight: 700 }}>家庭 MBTI</div>
        </div>
        <div style={{
          width: '14cqw', height: '14cqw', borderRadius: '2cqw',
          background: '#fff', padding: '1cqw',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {qrDataUrl ? (
            <img src={qrDataUrl} alt="扫码测试家庭 MBTI" style={{ width: '100%', height: '100%', display: 'block' }} />
          ) : (
            <div style={{ fontSize: '2.4cqw', color: '#2A1F14', fontWeight: 700 }}>QR</div>
          )}
        </div>
      </div>
    </div>
  );
}

// Share screen — overlay with the card + size toggle
function ShareScreen({ result, onClose, cardSize, setCardSize }) {
  const exportRef = React.useRef(null);
  const [qrDataUrl, setQrDataUrl] = React.useState('');
  const [imageUrl, setImageUrl] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [message, setMessage] = React.useState('');

  const shareUrl = React.useMemo(() => {
    const { origin, pathname } = window.location;
    return origin && origin !== 'null' ? `${origin}${pathname}` : window.location.href;
  }, []);

  React.useEffect(() => {
    let cancelled = false;

    if (!window.qrcode) {
      setMessage('二维码组件加载中，请稍后再试');
      return;
    }

    try {
      const qr = window.qrcode(0, 'M');
      qr.addData(shareUrl);
      qr.make();
      if (cancelled) return;
      setQrDataUrl(qr.createDataURL(8, 1));
      setMessage('');
    } catch (error) {
      if (!cancelled) setMessage('二维码生成失败，请刷新后重试');
    }

    return () => { cancelled = true; };
  }, [shareUrl]);

  const handleExport = async () => {
    if (!window.html2canvas) {
      setMessage('图片导出组件还没加载好，请稍后再试');
      return;
    }
    if (!qrDataUrl) {
      setMessage('二维码还在生成，请稍后再点一次');
      return;
    }
    if (!exportRef.current) return;

    setBusy(true);
    setMessage('');
    try {
      const canvas = await window.html2canvas(exportRef.current, {
        backgroundColor: null,
        scale: 1,
        useCORS: true,
      });
      setImageUrl(canvas.toDataURL('image/png'));
      setMessage('图片已生成，长按下方图片即可保存');
    } catch (error) {
      setMessage('图片生成失败，请刷新页面后重试');
    } finally {
      setBusy(false);
    }
  };

  const handleCopyLink = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl);
      setMessage('测试链接已复制');
    } catch (error) {
      setMessage(`复制失败，可以手动复制：${shareUrl}`);
    }
  };

  const exportHeight = cardSize === 'tall' ? 1920 : 1350;

  return (
    <div style={{
      width: '100%', minHeight: '100vh', position: 'relative',
      background: '#1A0F08',
      paddingTop: 40, paddingBottom: 30,
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '20px 20px 12px', position: 'relative', zIndex: 2,
      }}>
        <button onClick={onClose} style={{
          width: 32, height: 32, borderRadius: 16,
          background: 'rgba(255,255,255,0.12)', border: 'none', color: '#fff', flexShrink: 0,
          cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>✕</button>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, color: '#fff', fontSize: 15, whiteSpace: 'nowrap' }}>
          分享结果图
        </div>
        <div style={{ width: 32, flexShrink: 0 }} />
      </div>

      {/* Size toggle */}
      <div style={{
        display: 'flex', justifyContent: 'center', gap: 6, padding: '8px 20px',
      }}>
        {[
          { key: 'tall', label: '1080×1920', sub: '竖屏' },
          { key: 'square', label: '1080×1350', sub: '小红书' },
        ].map(opt => (
          <button key={opt.key} onClick={() => setCardSize(opt.key)} style={{
            padding: '8px 14px', borderRadius: 10,
            background: cardSize === opt.key ? '#FFF8EE' : 'rgba(255,255,255,0.08)',
            color: cardSize === opt.key ? '#2A1F14' : 'rgba(255,255,255,0.6)',
            border: 'none', cursor: 'pointer',
            fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 600,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1,
          }}>
            <span>{opt.label}</span>
            <span style={{ fontSize: 9, opacity: 0.7 }}>{opt.sub}</span>
          </button>
        ))}
      </div>

      {/* Card preview — use containerType to make cqw work */}
      <div style={{
        flex: 1, padding: '16px 24px', display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden',
      }}>
        <div style={{
          width: cardSize === 'tall' ? '78%' : '88%',
          containerType: 'inline-size',
          maxHeight: '100%',
        }}>
          <ShareCard result={result} size={cardSize} qrDataUrl={qrDataUrl} />
        </div>
      </div>

      {/* Action buttons */}
      <div style={{ padding: '12px 20px 0', display: 'flex', gap: 10 }}>
        <button onClick={handleExport} disabled={busy} style={{
          flex: 1, height: 50, borderRadius: 25,
          background: '#FFF8EE', color: '#2A1F14', border: 'none',
          fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 600,
          cursor: busy ? 'wait' : 'pointer', letterSpacing: 1, opacity: busy ? 0.7 : 1,
        }}>{busy ? '生成中…' : '📥 生成保存图'}</button>
        <button onClick={handleCopyLink} style={{
          flex: 1, height: 50, borderRadius: 25,
          background: 'rgba(255,255,255,0.12)', color: '#fff', border: 'none',
          fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 600,
          cursor: 'pointer', letterSpacing: 1,
        }}>🔗 复制链接</button>
      </div>
      <div style={{
        textAlign: 'center', marginTop: 10, fontSize: 10,
        color: 'rgba(255,255,255,0.4)', fontFamily: 'var(--font-body)',
      }}>{message || '生成后长按图片保存 · 二维码会带上测试入口'}</div>

      <div style={{
        position: 'fixed', left: -12000, top: 0,
        width: 1080, height: exportHeight,
        containerType: 'inline-size',
        pointerEvents: 'none',
      }}>
        <div ref={exportRef} style={{ width: 1080, height: exportHeight, containerType: 'inline-size' }}>
          <ShareCard result={result} size={cardSize} qrDataUrl={qrDataUrl} />
        </div>
      </div>

      {imageUrl && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 20,
          background: 'rgba(26,15,8,0.94)',
          display: 'flex', flexDirection: 'column',
          padding: '34px 20px 24px',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <div style={{ color: '#FFF8EE', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>
              长按图片保存
            </div>
            <button onClick={() => setImageUrl('')} style={{
              width: 34, height: 34, borderRadius: 17,
              border: 'none', background: 'rgba(255,255,255,0.14)',
              color: '#fff', fontSize: 16, cursor: 'pointer',
            }}>✕</button>
          </div>
          <div style={{
            flex: 1, minHeight: 0, overflow: 'auto',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <img src={imageUrl} alt="家庭 MBTI 分享图" style={{
              maxWidth: '100%', maxHeight: '100%',
              borderRadius: 18, boxShadow: '0 18px 50px rgba(0,0,0,0.42)',
              WebkitTouchCallout: 'default',
            }} />
          </div>
          <div style={{
            color: 'rgba(255,248,238,0.62)', textAlign: 'center',
            fontFamily: 'var(--font-body)', fontSize: 12, marginTop: 14,
          }}>保存后发给朋友，对方可扫码进入测试</div>
        </div>
      )}
    </div>
  );
}

window.ShareCard = ShareCard;
window.ShareScreen = ShareScreen;
