// 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';
const MASTER_ROOT = { 11: 2, 22: 4, 33: 6 };

function isMasterNumber(n) {
  return n === 11 || n === 22 || n === 33;
}

function toDisplayNumber(n) {
  return isMasterNumber(n) ? `${n}/${MASTER_ROOT[n]}` : String(n);
}

function toPlotNumber(n) {
  return MASTER_ROOT[n] || n;
}

// ─────────────────────────────────────────────────────────────
// 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 || {};
  const profile = Content.computeUserProfile ? Content.computeUserProfile(user || {}) : null;

  // 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: 7, personality: 7, destiny: 7, 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] || {};
    const dynamicTips = Content.buildDynamicTips ? Content.buildDynamicTips(role, n, profile) : null;
    return {
      key: role,
      n,
      displayN: toDisplayNumber(n),
      isMaster: isMasterNumber(n),
      plotN: toPlotNumber(n),
      label: r.label || role,
      vi: r.vi || '',
      short: c.short || c.tagline || '',
      body: {
        'Tính cách': ((dynamicTips && dynamicTips.personality) || (c.sections && c.sections['Tính cách cốt lõi']) || c.tagline || ''),
        'Điểm mạnh': ((dynamicTips && dynamicTips.strength) || (c.sections && c.sections['Sự nghiệp']) || ''),
        'Lưu ý': ((dynamicTips && dynamicTips.caution) || (c.sections && c.sections['Tình cảm']) || ''),
      },
    };
  });
}

function getUserNumbers(user) {
  const N = (typeof window !== 'undefined' && window.SaladinNumerology) || {};
  if (user && user.numbers) return user.numbers;
  if (user && user.dob && N.calculateAll) {
    try { return N.calculateAll({ name: user.name || '', dob: user.dob }); }
    catch (e) { return null; }
  }
  return null;
}

function buildCrossSellCopy(user) {
  const nums = getUserNumbers(user) || { personalYear: 7, lifePath: 7 };
  const y = new Date().getFullYear();
  const py = nums.personalYear || 7;
  const life = nums.lifePath || 7;
  const titleByYear = {
    1: 'năm bắt đầu mới',
    2: 'năm hợp tác và cân bằng',
    3: 'năm mở rộng kết nối',
    4: 'năm xây nền tảng',
    5: 'năm nhiều thay đổi',
    6: 'năm trách nhiệm gia đình',
    7: 'năm đào sâu nội lực',
    8: 'năm tài chính và thành tựu',
    9: 'năm hoàn tất chu kỳ',
    11: 'năm trực giác mạnh',
    22: 'năm kiến tạo dài hạn',
    33: 'năm phụng sự và chữa lành',
  };
  const tipByYear = {
    1: 'ưu tiên các kế hoạch tạo đà dài hạn và bảo vệ thu nhập khi bắt đầu chu kỳ mới.',
    2: 'tập trung kế hoạch tài chính an toàn, linh hoạt cho gia đình và các mối quan hệ.',
    3: 'cân bằng chi tiêu trải nghiệm với một lớp bảo vệ rủi ro sức khỏe cơ bản.',
    4: 'thiết kế ngân sách kỷ luật và khóa nền tảng bảo vệ dài hạn.',
    5: 'giữ quỹ dự phòng lớn hơn bình thường để hấp thụ biến động.',
    6: 'ưu tiên bảo vệ cho người thân trước, sau đó mới tối ưu tăng trưởng.',
    7: 'phù hợp các quyết định cẩn trọng, dựa trên phân tích dữ liệu.',
    8: 'nên kết hợp tăng trưởng tài sản với bảo vệ trách nhiệm tài chính.',
    9: 'phù hợp rà soát lại danh mục và chốt các kế hoạch đã kéo dài nhiều năm.',
    11: 'đặt trực giác cạnh số liệu để ra quyết định cân bằng.',
    22: 'đầu tư vào cấu trúc bảo vệ đủ lớn cho mục tiêu đường dài.',
    33: 'giữ ổn định tài chính cá nhân để duy trì khả năng chăm lo cho người khác.',
  };
  return {
    title: `${y}: ${titleByYear[py] || 'chu kỳ tài chính cá nhân'}?`,
    body: `Personal Year ${py} và Life Path ${life} của bạn cho thấy giai đoạn này ${tipByYear[py] || 'nên ưu tiên chiến lược an toàn, rõ mục tiêu và có lớp bảo vệ rủi ro.'}`,
  };
}


// ─────────────────────────────────────────────────────────────
// 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.plotN);
  const radarLabels = ['Life', 'Soul', 'Pers.', 'Dest.', 'PY'];
  const masterRoot = lifePath.isMaster ? MASTER_ROOT[lifePath.n] : null;
  const heroPrimaryNumber = lifePath.isMaster ? String(masterRoot) : (lifePath.displayN || String(lifePath.n));

  return (
    <div data-export="summary" 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: 'var(--primary-95)',
        borderRadius: 12,
        padding: mobile ? '16px 14px' : '18px 16px',
        minHeight: mobile ? 120 : 126,
        display: 'flex', alignItems: 'center', gap: 16,
        border: '1px solid var(--primary-90)',
        overflow: 'hidden',
      }}>
        <GridPattern size={180} opacity={0.05} color="var(--primary-70)" style={{ right: -28, bottom: -28 }} />
        <div style={{
          fontFamily: 'var(--font-display)', fontWeight: 900,
          fontSize: lifePath.isMaster ? (mobile ? 54 : 60) : (mobile ? 86 : 92), lineHeight: 0.9, color: 'var(--navy-40)',
          letterSpacing: '-0.05em', fontVariantNumeric: 'tabular-nums',
          flexShrink: 0, position: 'relative',
          width: lifePath.isMaster ? (mobile ? 110 : 124) : (mobile ? 82 : 86),
          textAlign: 'center',
        }}>{heroPrimaryNumber}</div>
        <div style={{ position: 'relative' }}>
          <div style={{
            fontSize: 10, fontWeight: 600, letterSpacing: '0.1em',
            textTransform: 'uppercase', color: 'var(--navy-40)', opacity: 0.72,
          }}>Con số chủ đạo</div>
          {lifePath.isMaster && (
            <div style={{ marginTop: 2, fontSize: 11, fontWeight: 600, color: 'var(--text-support)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <i className="ri-sparkling-2-line" style={{ fontSize: 11 }}></i>
              {`Master ${lifePath.n}`}
            </div>
          )}
          <div style={{ fontSize: 13, color: 'var(--text-support)', marginTop: 6, lineHeight: 1.35 }}>
            {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>
        {NUMBERS.some((n) => n.isMaster) && (
          <div style={{ marginTop: 8, fontSize: 11, color: 'var(--text-support)' }}>
            * Số Master hiển thị dạng 11/2, 22/4, 33/6: trước là Master, sau là số gốc để vẽ biểu đồ.
          </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={{
              minWidth: num.isMaster ? 34 : 24, height: 24, borderRadius: 6,
              padding: num.isMaster ? '0 6px' : 0,
              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: num.isMaster ? 11 : 12,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>{num.displayN}</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.displayN}
          </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.displayN || num.n}</div>

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 20, position: 'relative' }}>
        <div style={{
          minWidth: num.isMaster ? 98 : 64, height: 64, borderRadius: 12,
          padding: num.isMaster ? '0 12px' : 0,
          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: num.isMaster ? 30 : 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',
          whiteSpace: 'nowrap',
          lineHeight: 1,
        }}>{num.displayN || 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.displayN || num.n}
          <i className="ri-arrow-right-line" style={{ fontSize: 14 }}></i>
        </button>
      )}
    </article>
  );
}

// ─────────────────────────────────────────────────────────────
// CTA — Download PDF (needs email)
// ─────────────────────────────────────────────────────────────
function PdfCta({ onExportPdf }) {

  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 PDF nội dung chính
          </h3>
          <div style={{ fontSize: 13, color: 'var(--text-support)', marginTop: 2 }}>
            Xuất phần kết quả chính (không gồm header/footer)
          </div>
        </div>
      </div>

      <button
        type="button"
        onClick={onExportPdf}
        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',
        }}
      >
        Xuất PDF <i className="ri-file-pdf-line" style={{ fontSize: 16 }}></i>
      </button>

      <div style={{ fontSize: 11, color: 'var(--text-support)', marginTop: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
        <i className="ri-information-line" style={{ fontSize: 12 }}></i>
        Trình duyệt sẽ mở hộp thoại in. Chọn "Save as PDF" để lưu file.
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CTA — Soft Saladin cross-sell
// ─────────────────────────────────────────────────────────────
function SaladinCta({ user }) {
  const copy = buildCrossSellCopy(user);
  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',
      }}>
        {copy.title}
      </h3>
      <p style={{
        fontSize: 14, lineHeight: 1.6, margin: 0, marginBottom: 18,
        color: 'rgba(255,255,255,0.78)', position: 'relative', maxWidth: 480,
      }}>
        {copy.body}
      </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>
        ) : (
          <button
            onClick={onShare}
            style={{
              background: RES_SG, color: '#fff',
              padding: '10px 14px', borderRadius: 8, border: 'none',
              fontSize: 13, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
              fontFamily: 'inherit',
            }}
          >
            <i className="ri-share-forward-fill" style={{ fontSize: 14 }}></i>
            Chia sẻ
          </button>
        )}
      </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 kết quả'}
            </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: 'Bạn', dob: '1990-01-01', email: '' };
  const NUMBERS = buildNumbersFromUser(u);
  const exportMainResultPdf = () => {
    if (typeof window === 'undefined' || typeof document === 'undefined') return;
    document.body.classList.add('print-result-only');
    window.print();
    setTimeout(() => document.body.classList.remove('print-result-only'), 250);
  };
  React.useEffect(() => {
    if (typeof window === 'undefined') return undefined;
    window.SaladinExportResultPdf = exportMainResultPdf;
    return () => { delete window.SaladinExportResultPdf; };
  }, []);
  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%' }}>
      <div id="result-print-root">
        <EmailBanner mobile={mobile} user={u} />
        <ResultHero user={u} mobile={mobile} onBack={onBack} onShare={onShare} onPrint={exportMainResultPdf} />
        <div id="result-export-root" 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 onExportPdf={exportMainResultPdf} />
                <SaladinCta user={u} />
              </div>
            </div>
          </Container>
        </div>
      </div>
    </div>
  );
}

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

Object.assign(window, { ResultScreen });
