// Result screen — Kết quả phân tích thần số học
// Exports to window: ResultScreen

const RES_SG = '#14C560';
const RES_SN = '#1E3888';
const RES_SG_DEEP = '#005323';

// ─────────────────────────────────────────────────────────────
// Build numbers display data from user.numbers + content database
// ─────────────────────────────────────────────────────────────
function buildNumbersFromUser(user) {
  const N = (typeof window !== 'undefined' && window.SaladinNumerology) || {};
  const Content = (typeof window !== 'undefined' && window.SaladinContent) || {};
  const C = Content.NUMBER_CONTENT || {};
  const R = Content.ROLE_LABELS || {};

  // Priority:
  // 1. user.numbers (already computed by form submit)
  // 2. Auto-compute from user.name + user.dob (when navigating without form)
  // 3. Hardcoded fallback (last resort — should never hit in practice)
  let numbers = user && user.numbers ? user.numbers : null;
  if (!numbers && user && user.dob && N.calculateAll) {
    try {
      numbers = N.calculateAll({ name: user.name || '', dob: user.dob });
    } catch (e) { /* ignore */ }
  }
  const fallback = { lifePath: 7, soulUrge: 9, personality: 4, destiny: 1, personalYear: 7 };
  const nums = numbers || fallback;

  const roles = ['lifePath', 'soulUrge', 'personality', 'destiny', 'personalYear'];
  return roles.map((role) => {
    const n = nums[role] || 7;
    const c = C[n] || C[7] || {};
    const r = R[role] || {};
    return {
      key: role,
      n,
      label: r.label || role,
      vi: r.vi || '',
      short: c.short || c.tagline || '',
      body: {
        'Tính cách': (c.sections && c.sections['Tính cách cốt lõi']) || c.tagline || '',
        'Điểm mạnh': (c.sections && c.sections['Sự nghiệp']) || '',
        'Lưu ý': (c.sections && c.sections['Tình cảm']) || '',
      },
    };
  });
}


// ─────────────────────────────────────────────────────────────
// Pentagon radar chart for 5 numbers
// ─────────────────────────────────────────────────────────────
function NumberRadar({ values, labels, size = 240 }) {
  // values: array of 5 numbers (1-9); labels: array of 5 short strings
  const c = size / 2;
  const r = size * 0.36;
  const pts = values.map((v, i) => {
    const angle = -Math.PI / 2 + (i * 2 * Math.PI) / 5;
    const radius = (v / 9) * r;
    return { x: c + Math.cos(angle) * radius, y: c + Math.sin(angle) * radius, angle, v };
  });
  const labelPts = values.map((v, i) => {
    const angle = -Math.PI / 2 + (i * 2 * Math.PI) / 5;
    return { x: c + Math.cos(angle) * (r + 22), y: c + Math.sin(angle) * (r + 22), angle, anchor: i === 0 ? 'middle' : (i < 3 ? 'start' : (i === 3 ? 'end' : (i === 4 ? 'end' : 'middle'))) };
  });

  const rings = [0.33, 0.66, 1.0];
  const ringPath = (factor) => Array.from({ length: 5 }).map((_, i) => {
    const angle = -Math.PI / 2 + (i * 2 * Math.PI) / 5;
    return `${c + Math.cos(angle) * r * factor},${c + Math.sin(angle) * r * factor}`;
  }).join(' ');
  const valuePath = pts.map(p => `${p.x},${p.y}`).join(' ');

  return (
    <svg viewBox={`0 0 ${size} ${size}`} width="100%" style={{ maxWidth: size, display: 'block' }} aria-hidden="true">
      {/* Grid rings */}
      {rings.map(f => (
        <polygon key={f} points={ringPath(f)} fill="none" stroke="var(--border-default)" strokeWidth="1" />
      ))}
      {/* Axes */}
      {Array.from({ length: 5 }).map((_, i) => {
        const angle = -Math.PI / 2 + (i * 2 * Math.PI) / 5;
        return (
          <line key={i}
            x1={c} y1={c}
            x2={c + Math.cos(angle) * r}
            y2={c + Math.sin(angle) * r}
            stroke="var(--border-default)" strokeWidth="1"
          />
        );
      })}
      {/* Value shape */}
      <polygon points={valuePath} fill={RES_SG} fillOpacity="0.18" stroke={RES_SG} strokeWidth="2" strokeLinejoin="round"/>
      {/* Value dots */}
      {pts.map((p, i) => (
        <g key={i}>
          <circle cx={p.x} cy={p.y} r="6" fill={RES_SG} />
          <circle cx={p.x} cy={p.y} r="3" fill="#fff" />
        </g>
      ))}
      {/* Number labels at corners */}
      {pts.map((p, i) => (
        <g key={`l-${i}`}>
          <text
            x={labelPts[i].x} y={labelPts[i].y}
            fill="var(--text-default)"
            fontFamily="var(--font-display)" fontWeight="700" fontSize="14"
            textAnchor={labelPts[i].anchor}
            dominantBaseline="central"
          >{p.v}</text>
          <text
            x={labelPts[i].x} y={labelPts[i].y + 14}
            fill="var(--text-support)"
            fontFamily="var(--font-sans)" fontWeight="500" fontSize="9"
            textAnchor={labelPts[i].anchor}
            dominantBaseline="central"
          >{labels[i]}</text>
        </g>
      ))}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Summary card (sticky on desktop, inline on mobile)
// ─────────────────────────────────────────────────────────────
function SummaryCard({ user, mobile, onOpenDetail }) {
  const NUMBERS = buildNumbersFromUser(user);
  const lifePath = NUMBERS[0];
  const radarValues = NUMBERS.map(n => n.n);
  const radarLabels = ['Life', 'Soul', 'Pers.', 'Dest.', 'PY'];

  return (
    <div style={{
      background: 'var(--bg)',
      border: '1px solid var(--border-default)',
      borderRadius: 16,
      padding: mobile ? 20 : 24,
      boxShadow: 'var(--shadow-sm)',
      display: 'flex', flexDirection: 'column', gap: 20,
    }}>
      {/* User row */}
      <div>
        <div style={{
          fontSize: 11, fontWeight: 600, textTransform: 'uppercase',
          letterSpacing: '0.1em', color: 'var(--text-support)', marginBottom: 6,
        }}>Phân tích cho</div>
        <div style={{
          fontFamily: 'var(--font-display)', fontWeight: 700,
          fontSize: 22, lineHeight: 1.2, color: 'var(--text-default)',
        }}>{user.name}</div>
        <div style={{ fontSize: 13, color: 'var(--text-support)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}>
          <i className="ri-calendar-line" style={{ fontSize: 14 }}></i>
          {formatVNDate(user.dob)}
        </div>
      </div>

      {/* Big life-path number */}
      <div style={{
        position: 'relative',
        background: 'linear-gradient(135deg, var(--hero-card-grad-from) 0%, var(--hero-card-grad-to) 100%)',
        borderRadius: 12,
        padding: '20px 16px',
        display: 'flex', alignItems: 'center', gap: 16,
        border: '1px solid var(--primary-95)',
        overflow: 'hidden',
      }}>
        <GridPattern size={180} opacity={0.06} color={RES_SN} style={{ right: -30, bottom: -30 }} />
        <div style={{
          fontFamily: 'var(--font-display)', fontWeight: 900,
          fontSize: 88, lineHeight: 0.9, color: RES_SN,
          letterSpacing: '-0.05em', fontVariantNumeric: 'tabular-nums',
          textShadow: '0 4px 16px rgba(30,56,136,0.10)',
          flexShrink: 0, position: 'relative',
        }}>{lifePath.n}</div>
        <div style={{ position: 'relative' }}>
          <div style={{
            fontSize: 10, fontWeight: 600, letterSpacing: '0.1em',
            textTransform: 'uppercase', color: RES_SN, opacity: 0.7,
          }}>Con số chủ đạo</div>
          <div style={{
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: 18, lineHeight: 1.2, color: RES_SN, marginTop: 4,
          }}>Life Path 7</div>
          <div style={{ fontSize: 12, color: 'var(--text-support)', marginTop: 4, lineHeight: 1.4 }}>
            {lifePath.short}
          </div>
        </div>
      </div>

      {/* Radar chart */}
      <div>
        <div style={{
          fontSize: 11, fontWeight: 600, textTransform: 'uppercase',
          letterSpacing: '0.1em', color: 'var(--text-support)', marginBottom: 10,
        }}>Biểu đồ 5 con số</div>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <NumberRadar values={radarValues} labels={radarLabels} size={mobile ? 220 : 240} />
        </div>
      </div>

      {/* Mini legend */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
        {NUMBERS.map((num, i) => (
          <a key={num.key} href={`#${num.key}`}
            onClick={(e) => {
              const card = document.getElementById(num.key);
              if (card) {
                e.preventDefault();
                card.scrollIntoView({ block: 'start' });
              }
            }}
            style={{
              display: 'flex', alignItems: 'center', gap: 8,
              padding: '6px 8px', borderRadius: 6,
              background: 'var(--bg-variant)', textDecoration: 'none',
            }}>
            <span style={{
              width: 24, height: 24, borderRadius: 6,
              background: i === 0 ? RES_SG : 'var(--bg)',
              border: i === 0 ? 'none' : '1px solid var(--border-default)',
              color: i === 0 ? '#fff' : 'var(--text-default)',
              fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>{num.n}</span>
            <span style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-default)', lineHeight: 1.3 }}>
              {num.vi}
            </span>
          </a>
        ))}
      </div>

      {/* Open detail of life path */}
      {onOpenDetail && (
        <button
          onClick={() => onOpenDetail(lifePath.n)}
          style={{
            background: 'var(--bg-variant)',
            border: '1px solid var(--border-default)',
            borderRadius: 8,
            padding: '12px 14px',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
            cursor: 'pointer', fontFamily: 'inherit',
            color: 'var(--text-default)',
            transition: 'border-color 150ms, background 150ms',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.borderColor = RES_SG; }}
          onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border-default)'; }}
        >
          <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600 }}>
            <i className="ri-article-line" style={{ fontSize: 16, color: RES_SG }}></i>
            Đọc đầy đủ về Life Path {lifePath.n}
          </span>
          <i className="ri-arrow-right-line" style={{ fontSize: 16, color: RES_SG }}></i>
        </button>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Number detail card
// ─────────────────────────────────────────────────────────────
function NumberCard({ num, index, onOpenDetail }) {
  const sections = ['Tính cách', 'Điểm mạnh', 'Lưu ý'];
  const sectionIcons = {
    'Tính cách': 'ri-user-3-line',
    'Điểm mạnh': 'ri-flashlight-line',
    'Lưu ý': 'ri-alert-line',
  };
  const sectionColors = {
    'Tính cách': RES_SN,
    'Điểm mạnh': RES_SG_DEEP,
    'Lưu ý': '#A29200',
  };

  return (
    <article id={num.key} style={{
      background: 'var(--bg)',
      border: '1px solid var(--border-default)',
      borderRadius: 16,
      padding: 28,
      boxShadow: 'var(--shadow-xs)',
      position: 'relative',
      overflow: 'hidden',
      scrollMarginTop: 90,
    }}>
      {/* Watermark number */}
      <div style={{
        position: 'absolute', right: -10, top: -40,
        fontFamily: 'var(--font-display)', fontWeight: 900,
        fontSize: 240, lineHeight: 1, color: 'var(--watermark)',
        letterSpacing: '-0.05em', pointerEvents: 'none',
        fontVariantNumeric: 'tabular-nums',
      }}>{num.n}</div>

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 20, position: 'relative' }}>
        <div style={{
          width: 64, height: 64, borderRadius: 12,
          background: index === 0 ? RES_SG : 'var(--bg-variant)',
          border: index === 0 ? 'none' : '1px solid var(--border-default)',
          color: index === 0 ? '#fff' : RES_SN,
          fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 36,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
          boxShadow: index === 0 ? '0 4px 12px -2px rgba(20,197,96,0.35)' : 'none',
          fontVariantNumeric: 'tabular-nums',
        }}>{num.n}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
            <span style={{
              display: 'inline-flex', alignItems: 'center',
              padding: '3px 10px', borderRadius: 50,
              background: index === 0 ? 'var(--primary-95)' : 'var(--bg-variant)',
              color: index === 0 ? RES_SG_DEEP : 'var(--text-support)',
              fontSize: 11, fontWeight: 600, letterSpacing: '0.04em',
            }}>{num.label}</span>
            {index === 0 && (
              <span style={{
                fontSize: 11, color: RES_SG, fontWeight: 600,
                textTransform: 'uppercase', letterSpacing: '0.08em',
              }}>· Quan trọng nhất</span>
            )}
          </div>
          <h3 style={{
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: 26, lineHeight: 1.15, margin: 0, color: 'var(--text-default)',
            letterSpacing: '-0.015em',
          }}>{num.vi}</h3>
          <div style={{ fontSize: 14, color: 'var(--text-support)', marginTop: 4 }}>{num.short}</div>
        </div>
      </div>

      {/* Body sections */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16, position: 'relative' }}>
        {sections.map(s => (
          <div key={s}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 6,
              fontSize: 12, fontWeight: 700, textTransform: 'uppercase',
              letterSpacing: '0.08em', color: sectionColors[s], marginBottom: 6,
            }}>
              <i className={sectionIcons[s]} style={{ fontSize: 14 }}></i>
              {s}
            </div>
            <p style={{
              fontSize: 14, lineHeight: 1.65, margin: 0,
              color: 'var(--text-default)', textWrap: 'pretty',
            }}>{num.body[s]}</p>
          </div>
        ))}
      </div>

      {/* Read more link */}
      {onOpenDetail && (
        <button
          onClick={() => onOpenDetail(num.n)}
          style={{
            marginTop: 20, padding: 0,
            background: 'transparent', border: 'none', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 6,
            fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
            color: RES_SG, position: 'relative',
          }}
        >
          Đọc đầy đủ về {num.label} {num.n}
          <i className="ri-arrow-right-line" style={{ fontSize: 14 }}></i>
        </button>
      )}
    </article>
  );
}

// ─────────────────────────────────────────────────────────────
// CTA — Download PDF (needs email)
// ─────────────────────────────────────────────────────────────
function PdfCta({ user }) {
  const [email, setEmail] = React.useState(user.email || '');
  const [sent, setSent] = React.useState(false);

  return (
    <div style={{
      background: 'var(--bg)',
      border: `2px solid ${RES_SG}`,
      borderRadius: 16,
      padding: 28,
      boxShadow: '0 4px 12px -2px rgba(20,197,96,0.18)',
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 10, background: 'var(--primary-95)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <i className="ri-file-pdf-line" style={{ fontSize: 22, color: RES_SG_DEEP }}></i>
        </div>
        <div>
          <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, margin: 0, color: 'var(--text-default)' }}>
            Tải báo cáo PDF đầy đủ
          </h3>
          <div style={{ fontSize: 13, color: 'var(--text-support)', marginTop: 2 }}>
            Bản phân tích 12 trang · gửi ngay vào email
          </div>
        </div>
      </div>

      {sent ? (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '12px 14px', background: 'var(--primary-95)',
          borderRadius: 8, color: RES_SG_DEEP, fontSize: 14, fontWeight: 500,
        }}>
          <i className="ri-checkbox-circle-fill" style={{ fontSize: 18 }}></i>
          Đã gửi báo cáo PDF đến {email}. Kiểm tra hộp thư trong 1-2 phút.
        </div>
      ) : (
        <form onSubmit={(e) => { e.preventDefault(); if (email) setSent(true); }}
              style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <input
            type="email" required value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="email@cua-ban.com"
            style={{
              flex: '1 1 220px',
              padding: '12px 14px',
              border: '1px solid var(--border-default)',
              borderRadius: 8, background: 'var(--bg)',
              fontSize: 14, fontFamily: 'inherit', color: 'var(--text-default)',
              outline: 'none', minWidth: 0,
            }}
          />
          <button type="submit" style={{
            background: RES_SG, color: '#fff',
            padding: '12px 20px', borderRadius: 4, border: 'none',
            fontFamily: 'inherit', fontSize: 14, fontWeight: 600, cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap',
          }}>
            Gửi báo cáo <i className="ri-send-plane-fill" style={{ fontSize: 16 }}></i>
          </button>
        </form>
      )}

      <div style={{ fontSize: 11, color: 'var(--text-support)', marginTop: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
        <i className="ri-lock-2-line" style={{ fontSize: 12 }}></i>
        Saladin không chia sẻ email của bạn cho bên thứ ba.
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CTA — Soft Saladin cross-sell
// ─────────────────────────────────────────────────────────────
function SaladinCta() {
  return (
    <div style={{
      background: 'var(--xsell-bg)',
      borderRadius: 16, padding: 28, color: '#fff',
      position: 'relative', overflow: 'hidden',
      border: '1px solid var(--xsell-border)',
    }}>
      <GridPattern size={240} opacity={0.06} color="#fff" style={{ right: -40, bottom: -50 }} />
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '4px 10px', background: 'rgba(255,255,255,0.10)',
        border: '1px solid rgba(255,255,255,0.18)',
        borderRadius: 50, fontSize: 11, fontWeight: 600, color: 'rgba(255,255,255,0.92)',
        textTransform: 'uppercase', letterSpacing: '0.08em', position: 'relative',
      }}>
        <i className="ri-lightbulb-flash-line" style={{ fontSize: 13 }}></i>
        Gợi ý từ Saladin
      </span>
      <h3 style={{
        fontFamily: 'var(--font-display)', fontWeight: 700,
        fontSize: 22, lineHeight: 1.2,
        margin: '14px 0 8px', color: '#fff', letterSpacing: '-0.01em',
        position: 'relative',
      }}>
        2026 hợp đầu tư dài hạn?
      </h3>
      <p style={{
        fontSize: 14, lineHeight: 1.6, margin: 0, marginBottom: 18,
        color: 'rgba(255,255,255,0.78)', position: 'relative', maxWidth: 480,
      }}>
        Personal Year 7 của bạn là chu kỳ "đào sâu" — thường phù hợp với những quyết định cẩn trọng như mua bảo hiểm sức khoẻ hoặc hợp đồng nhân thọ.
      </p>
      <a href="https://saladin.vn" style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        background: 'transparent', color: '#fff',
        padding: '10px 16px', borderRadius: 4,
        border: '1px solid rgba(255,255,255,0.45)',
        fontSize: 14, fontWeight: 600, position: 'relative',
      }}>
        Xem các gói Saladin <i className="ri-arrow-right-line" style={{ fontSize: 16 }}></i>
      </a>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Result top hero (slim)
// ─────────────────────────────────────────────────────────────
function ResultHero({ user, mobile, onBack, onShare, onPrint }) {
  return (
    <div style={{
      background: 'var(--hero-bg)',
      paddingTop: mobile ? 20 : 32,
      paddingBottom: mobile ? 20 : 32,
      borderBottom: '1px solid var(--border-default)',
    }}>
      <Container style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <button
            type="button"
            onClick={onBack}
            style={{
              background: 'transparent', border: 'none', cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontSize: 12, fontWeight: 500, color: 'var(--text-support)',
              padding: 0, marginBottom: 8,
            }}
          >
            <i className="ri-arrow-left-line" style={{ fontSize: 14 }}></i>
            Tra cứu lại
          </button>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: mobile ? 22 : 28, lineHeight: 1.15,
            margin: 0, letterSpacing: '-0.02em', color: 'var(--text-default)',
          }}>
            Kết quả phân tích của <span style={{ color: RES_SG }}>{user.name.split(' ').slice(-1)[0]}</span>
          </h1>
          <div style={{ fontSize: 13, color: 'var(--text-support)', marginTop: 4 }}>
            Hoàn tất · 5 chỉ số · phương pháp Pythagorean
          </div>
        </div>
        {!mobile && (
          <div style={{ display: 'flex', gap: 10 }}>
            <button
              onClick={onPrint}
              style={{
                background: 'var(--bg)', color: 'var(--text-default)',
                padding: '0 16px', height: 40, borderRadius: 8,
                border: '1px solid var(--border-default)',
                fontSize: 13, fontWeight: 600,
                display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
                fontFamily: 'inherit',
                boxShadow: 'var(--shadow-xs)',
                transition: 'border-color 150ms, box-shadow 150ms, transform 150ms',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--border-strong)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border-default)'; }}
            >
              <span style={{
                width: 22, height: 22, borderRadius: 6,
                background: 'var(--bg-variant)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <i className="ri-printer-line" style={{ fontSize: 14, color: 'var(--text-support)' }}></i>
              </span>
              <span>In báo cáo</span>
            </button>
            <button
              onClick={onShare}
              style={{
                background: RES_SG, color: '#fff',
                padding: '0 18px', height: 40, borderRadius: 8,
                border: 'none',
                fontSize: 13, fontWeight: 600,
                display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
                fontFamily: 'inherit',
                boxShadow: '0 4px 12px -2px rgba(20,197,96,0.35), inset 0 1px 0 rgba(255,255,255,0.18)',
                transition: 'transform 150ms, box-shadow 150ms',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 6px 16px -2px rgba(20,197,96,0.45), inset 0 1px 0 rgba(255,255,255,0.18)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)';   e.currentTarget.style.boxShadow = '0 4px 12px -2px rgba(20,197,96,0.35), inset 0 1px 0 rgba(255,255,255,0.18)'; }}
            >
              <span style={{
                width: 22, height: 22, borderRadius: 6,
                background: 'rgba(255,255,255,0.18)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <i className="ri-share-forward-fill" style={{ fontSize: 14, color: '#fff' }}></i>
              </span>
              <span>Chia sẻ kết quả</span>
            </button>
          </div>
        )}
      </Container>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────


// ─────────────────────────────────────────────────────────────
// BirthChartCard — Biểu đồ ngày sinh (matrix 3×3)
// ─────────────────────────────────────────────────────────────
function BirthChartCard({ user, mobile }) {
  if (typeof window === 'undefined' || !window.BirthChartMatrix) return null;
  return (
    <div style={{
      background: 'var(--bg)',
      border: '1px solid var(--border-default)',
      borderRadius: 16,
      padding: mobile ? 20 : 28,
      boxShadow: 'var(--shadow-xs)',
      position: 'relative',
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
        <span style={{
          padding: '3px 8px', background: 'var(--bg-variant)',
          border: '1px solid var(--border-default)', borderRadius: 50,
          fontSize: 10, fontWeight: 700, color: 'var(--text-support)',
          textTransform: 'uppercase', letterSpacing: '0.08em',
        }}>Bonus</span>
        <h3 style={{
          fontFamily: 'var(--font-display)', fontWeight: 700,
          fontSize: mobile ? 20 : 24, margin: 0,
          color: 'var(--text-default)',
        }}>
          Biểu đồ ngày sinh
        </h3>
      </div>
      <p style={{
        fontSize: mobile ? 13 : 14, color: 'var(--text-support)',
        margin: 0, marginBottom: 18, lineHeight: 1.5,
      }}>
        Ma trận 3×3 cho thấy các con số xuất hiện trong ngày sinh — mỗi nhóm số liên tiếp tạo thành "Mũi tên cá tính" phản ánh phẩm chất bẩm sinh.
      </p>
      {React.createElement(window.BirthChartMatrix, { dob: user.dob, mobile })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// EmailBanner — Sticky top banner for email capture (replaces popup)
// Dismissible — saves "saladin-banner-dismissed-until" for 7 days
// ─────────────────────────────────────────────────────────────
function EmailBanner({ mobile, user }) {
  const N = (typeof window !== 'undefined' && window.SaladinNumerology) || {};
  const [visible, setVisible] = React.useState(true);
  const [email, setEmail] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    // Read localStorage on mount
    if (N.shouldShowBanner && !N.shouldShowBanner()) setVisible(false);
  }, []);

  if (!visible) return null;

  const dismiss = () => {
    if (N.dismissBanner) N.dismissBanner();
    if (N.trackEvent) N.trackEvent('email_banner_dismissed', {});
    setVisible(false);
  };

  const submit = (e) => {
    e.preventDefault();
    if (!email || !/^\S+@\S+\.\S+$/.test(email)) return;
    setSubmitting(true);
    // In production: POST to /api/save-result
    if (N.trackEvent) N.trackEvent('email_capture', { source: 'result_banner' });
    setTimeout(() => {
      setSent(true);
      setSubmitting(false);
      // Auto-fade after 3s
      setTimeout(() => setVisible(false), 3000);
    }, 700);
  };

  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 40,
      background: 'var(--primary-95)',
      borderBottom: '1px solid var(--border-default)',
      padding: mobile ? '8px 16px' : '10px 24px',
      animation: 'fadeIn 250ms cubic-bezier(0.4,0,0.2,1)',
    }}>
      <div style={{
        maxWidth: 1280, margin: '0 auto',
        display: 'flex', alignItems: 'center', gap: mobile ? 8 : 16,
        flexDirection: mobile ? 'column' : 'row',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          flex: mobile ? 'none' : '0 1 auto',
          width: mobile ? '100%' : 'auto',
        }}>
          <i className="ri-mail-line" style={{ fontSize: 18, color: RES_SG_DEEP, flexShrink: 0 }}></i>
          <span style={{ fontSize: mobile ? 13 : 14, color: 'var(--text-default)', fontWeight: 500 }}>
            {sent ? (
              <><i className="ri-checkbox-circle-fill" style={{ color: RES_SG, marginRight: 4 }}></i>Đã gửi tới <strong>{email}</strong></>
            ) : (
              'Lưu kết quả về email để đọc lại sau'
            )}
          </span>
        </div>
        {!sent && (
          <form onSubmit={submit} style={{
            display: 'flex', gap: 8,
            flex: mobile ? 'none' : '1 1 auto',
            width: mobile ? '100%' : 'auto',
            maxWidth: mobile ? '100%' : 480,
          }}>
            <input
              type="email" required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="email@cua-ban.com"
              style={{
                flex: 1, minWidth: 0,
                padding: '8px 12px', borderRadius: 6,
                border: '1px solid var(--border-default)',
                background: 'var(--bg)',
                fontSize: 13, fontFamily: 'inherit',
                color: 'var(--text-default)', outline: 'none',
              }}
            />
            <button type="submit" disabled={submitting} style={{
              background: RES_SG, color: '#fff',
              padding: '8px 14px', borderRadius: 4, border: 'none',
              fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
              cursor: submitting ? 'wait' : 'pointer',
              whiteSpace: 'nowrap',
              opacity: submitting ? 0.7 : 1,
              display: 'inline-flex', alignItems: 'center', gap: 4,
            }}>
              {submitting ? <i className="ri-loader-4-line" style={{ animation: 'spin 800ms linear infinite' }}></i> : 'Gửi báo cáo PDF'}
            </button>
          </form>
        )}
        <button
          type="button"
          onClick={dismiss}
          aria-label="Đóng banner"
          style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            padding: 6, color: 'var(--text-support)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            position: mobile ? 'absolute' : 'static',
            top: mobile ? 4 : 'auto', right: mobile ? 8 : 'auto',
          }}
        >
          <i className="ri-close-line" style={{ fontSize: 18 }}></i>
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PosterCta — CTA card sending users to Poster Generator
// ─────────────────────────────────────────────────────────────
function PosterCta({ user, onOpen, mobile }) {
  return (
    <div style={{
      background: 'var(--bg)',
      border: `2px dashed ${RES_SG}`,
      borderRadius: 16,
      padding: mobile ? 20 : 24,
      position: 'relative', overflow: 'hidden',
      display: 'flex',
      flexDirection: mobile ? 'column' : 'row',
      alignItems: mobile ? 'flex-start' : 'center',
      gap: 16,
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: 14,
        background: 'var(--primary-95)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <i className="ri-image-2-line" style={{ fontSize: 28, color: RES_SG_DEEP }}></i>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <h3 style={{
          fontFamily: 'var(--font-display)', fontWeight: 700,
          fontSize: mobile ? 18 : 20, margin: 0, marginBottom: 4,
          color: 'var(--text-default)',
        }}>
          Khoe con số của bạn lên social
        </h3>
        <div style={{ fontSize: 13, color: 'var(--text-support)', lineHeight: 1.5 }}>
          Tạo poster cá nhân hoá cho Facebook, Zalo, TikTok — đẹp như một designer pro.
        </div>
      </div>
      <button
        type="button"
        onClick={() => onOpen && onOpen()}
        style={{
          background: RES_SG, color: '#fff',
          padding: '12px 20px', borderRadius: 4, border: 'none',
          fontFamily: 'inherit', fontSize: 14, fontWeight: 600,
          cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', gap: 8,
          whiteSpace: 'nowrap', flexShrink: 0,
          boxShadow: '0 4px 12px -2px rgba(20,197,96,0.35)',
          width: mobile ? '100%' : 'auto',
          justifyContent: 'center',
        }}
      >
        Tạo poster ngay
        <i className="ri-arrow-right-line" style={{ fontSize: 16 }}></i>
      </button>
    </div>
  );
}

// Main ResultScreen
// ─────────────────────────────────────────────────────────────
function ResultScreen({ mobile, user, onBack, onShare, onOpenDetail, onOpenPoster }) {
  const u = user || { name: 'Nguyễn Hoài An', dob: '1990-10-28', email: '' };
  const NUMBERS = buildNumbersFromUser(u);
  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%' }}>
      <EmailBanner mobile={mobile} user={u} />
      <ResultHero user={u} mobile={mobile} onBack={onBack} onShare={onShare} onPrint={() => window.print()} />
      <div style={{ padding: mobile ? '24px 0 48px' : '40px 0 80px' }}>
        <Container>
          <div style={{
            display: 'grid',
            gridTemplateColumns: mobile ? '1fr' : '360px 1fr',
            gap: mobile ? 20 : 32,
            alignItems: 'flex-start',
          }}>
            {/* LEFT: sticky summary */}
            <aside style={{ position: mobile ? 'static' : 'sticky', top: mobile ? 0 : 80 }}>
              <SummaryCard user={u} mobile={mobile} onOpenDetail={onOpenDetail} />
            </aside>

            {/* RIGHT: scrolling number cards + CTAs */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: mobile ? 16 : 20, minWidth: 0 }}>
              {NUMBERS.map((num, i) => (
                <NumberCard key={num.key} num={num} index={i} onOpenDetail={onOpenDetail} />
              ))}

              {/* Birth Chart matrix — visual signature of numerology */}
              <BirthChartCard user={u} mobile={mobile} />

              {/* CTAs at end */}
              <PosterCta user={u} onOpen={onOpenPoster} mobile={mobile} />
              <PdfCta user={u} />
              <SaladinCta />
            </div>
          </div>
        </Container>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────
function formatVNDate(iso) {
  if (!iso) return '';
  const [y, m, d] = iso.split('-');
  return `${d}/${m}/${y}`;
}

Object.assign(window, { ResultScreen });
