// Saladin Thần số — Birth Chart matrix 3x3 (Pythagorean layout)
// Exports: BirthChartMatrix component
//
// Layout (Pythagorean — match momo.vn convention):
//   3 | 6 | 9
//   2 | 5 | 8
//   1 | 4 | 7

function BirthChartMatrix({ dob, mobile, compact, showArrows = true }) {
  const Content = (typeof window !== 'undefined' && window.SaladinContent) || {};
  if (!Content.computeBirthChart || !dob) return null;

  const { counts, presentArrows, missingArrows } = Content.computeBirthChart(dob);
  const layout = Content.BIRTH_CHART_LAYOUT || [[3,6,9],[2,5,8],[1,4,7]];

  const cellSize = compact ? 44 : (mobile ? 56 : 72);
  const fontSize = compact ? 18 : (mobile ? 22 : 28);
  const totalSize = cellSize * 3;

  // Detect which arrows are present (for highlight overlay)
  const presentArrowDigits = new Set();
  presentArrows.forEach(a => {
    a.digits.forEach(d => presentArrowDigits.add(`${a.name}:${d}`));
  });

  return (
    <div style={{
      display: 'flex',
      flexDirection: compact ? 'row' : (mobile ? 'column' : 'row'),
      gap: compact ? 16 : (mobile ? 20 : 32),
      alignItems: compact ? 'center' : 'flex-start',
    }}>
      {/* Matrix */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: `repeat(3, ${cellSize}px)`,
        gridTemplateRows: `repeat(3, ${cellSize}px)`,
        gap: 2,
        background: 'var(--border-default)',
        border: '1px solid var(--border-default)',
        borderRadius: 8,
        overflow: 'hidden',
        flexShrink: 0,
      }}>
        {layout.flat().map((digit) => {
          const count = counts[digit] || 0;
          const has = count > 0;
          return (
            <div
              key={digit}
              style={{
                width: cellSize, height: cellSize,
                background: has ? 'var(--bg)' : 'var(--bg-variant)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                position: 'relative',
                color: has ? 'var(--text-default)' : 'var(--text-disabled, rgba(0,0,0,0.25))',
                fontFamily: 'var(--font-display)',
                fontSize, fontWeight: has ? 700 : 400,
                opacity: has ? 1 : 0.4,
              }}
              title={has ? `Số ${digit} xuất hiện ${count} lần` : `Số ${digit} không có`}
            >
              {has ? (
                <span>
                  {digit}
                  {count > 1 && (
                    <span style={{
                      position: 'absolute',
                      top: 4, right: 6,
                      fontSize: 10, fontWeight: 600,
                      color: '#14C560', fontFamily: 'var(--font-sans)',
                    }}>×{count}</span>
                  )}
                </span>
              ) : (
                <span style={{ opacity: 0.5 }}>·</span>
              )}
            </div>
          );
        })}
      </div>

      {/* Arrows legend */}
      {showArrows && !compact && (
        <div style={{
          flex: 1, minWidth: 0,
          fontSize: mobile ? 12 : 13,
        }}>
          {presentArrows.length > 0 && (
            <div style={{ marginBottom: missingArrows.length > 0 ? 14 : 0 }}>
              <div style={{
                fontSize: 11, fontWeight: 700,
                textTransform: 'uppercase', letterSpacing: '0.06em',
                color: '#005323', marginBottom: 6,
                display: 'flex', alignItems: 'center', gap: 4,
              }}>
                <i className="ri-arrow-right-up-line" style={{ fontSize: 14 }}></i>
                Mũi tên cá tính ({presentArrows.length})
              </div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 6 }}>
                {presentArrows.map((a) => (
                  <li key={a.name} style={{
                    display: 'flex', alignItems: 'flex-start', gap: 8,
                    padding: '6px 10px',
                    background: 'var(--primary-95)',
                    borderRadius: 6,
                    border: '1px solid var(--primary-90, #DDE5DA)',
                  }}>
                    <span style={{ fontSize: 11, color: '#005323', fontWeight: 700, flexShrink: 0 }}>
                      {a.digits.join('-')}
                    </span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ color: 'var(--text-default)', fontWeight: 600 }}>{a.name}</div>
                      <div style={{ color: 'var(--text-support)', fontSize: 11, marginTop: 1 }}>{a.desc}</div>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          )}

          {missingArrows.length > 0 && (
            <div>
              <div style={{
                fontSize: 11, fontWeight: 700,
                textTransform: 'uppercase', letterSpacing: '0.06em',
                color: 'var(--text-support)', marginBottom: 6,
                display: 'flex', alignItems: 'center', gap: 4,
              }}>
                <i className="ri-information-line" style={{ fontSize: 14 }}></i>
                Mũi tên cần cải thiện ({missingArrows.length})
              </div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 6 }}>
                {missingArrows.map((a) => (
                  <li key={a.name} style={{
                    display: 'flex', alignItems: 'flex-start', gap: 8,
                    padding: '6px 10px',
                    background: 'var(--bg-variant)',
                    borderRadius: 6,
                    border: '1px dashed var(--border-default)',
                  }}>
                    <span style={{ fontSize: 11, color: 'var(--text-support)', fontWeight: 700, flexShrink: 0 }}>
                      {a.digits.join('-')}
                    </span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ color: 'var(--text-default)', fontWeight: 600 }}>{a.name}</div>
                      <div style={{ color: 'var(--text-support)', fontSize: 11, marginTop: 1 }}>Cần luyện tập để phát triển {a.desc.toLowerCase().replace(/\.$/, '')}.</div>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          )}

          {presentArrows.length === 0 && missingArrows.length === 0 && (
            <div style={{ fontSize: 12, color: 'var(--text-support)', fontStyle: 'italic' }}>
              Chưa phát hiện mũi tên nào — bạn có biểu đồ cân bằng tự nhiên.
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// Compact version for Summary card (matrix only, no legend)
function BirthChartCompact({ dob }) {
  return <BirthChartMatrix dob={dob} compact showArrows={false} />;
}

Object.assign(window, { BirthChartMatrix, BirthChartCompact });
