/**
 * 日历热力图（plan.md「5.2 日历热力图」）。
 * 按日期展示消费强度（颜色深浅）。
 */
import React, { useMemo } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { getMonthGrid } from '../../domain/calendarGrid';
import { dailyExpenseMap } from '../../domain/chartStats';
import type { Transaction } from '../../domain/types';

/** 根据强度返回颜色（0-1）。使用 opacity 而非字符串替换，兼容 hex 和 rgb。 */
function heatColor(intensity: number): { opacity: number } {
  if (intensity <= 0) return { opacity: 0 };
  return { opacity: Math.min(0.2 + intensity * 0.8, 1) };
}

export function CalendarHeatmap({ transactions, year, month }: { transactions: Transaction[]; year: number; month: number }) {
  const { theme } = useTheme();
  const t = useT();
  // 星期头周日起（与 getMonthGrid 网格一致），文案走 i18n
  const weekdays = useMemo(() => t('calendar.weekdays').split(','), [t]);
  const dailyMap = useMemo(() => dailyExpenseMap(transactions), [transactions]);
  const weeks = useMemo(() => getMonthGrid(year, month, transactions), [year, month, transactions]);
  const maxDaily = Math.max(...dailyMap.values(), 1);

  return (
    <View style={[styles.container, { backgroundColor: theme.colors.bgSecondary, borderRadius: theme.radii.md, padding: theme.spacing.sm }]}>
      <Text style={[theme.typography.h3, { color: theme.colors.fgPrimary, marginBottom: 4 }]}>
        {t('report.heatmap')}
      </Text>
      <View style={styles.weekdayRow}>
        {weekdays.map(d => (
          <Text key={d} style={[theme.typography.caption, { color: theme.colors.fgSecondary, textAlign: 'center', flex: 1, fontSize: 10 }]}>
            {d}
          </Text>
        ))}
      </View>
      {weeks.map((week, wi) => (
        <View key={wi} style={styles.weekRow}>
          {week.map(cell => {
            const expense = dailyMap.get(cell.date) ?? 0;
            const intensity = expense / maxDaily;
            return (
              <View key={cell.date} style={[
                styles.cell,
                {
                  backgroundColor: cell.isCurrentMonth && expense > 0
                    ? theme.colors.financial.expense
                    : 'transparent',
                  borderColor: theme.colors.border,
                  opacity: cell.isCurrentMonth ? (expense > 0 ? heatColor(intensity).opacity : 1) : 0.3,
                },
              ]}>
                <Text style={[theme.typography.caption, { fontSize: 10, color: theme.colors.fgSecondary }]}>
                  {cell.day}
                </Text>
              </View>
            );
          })}
        </View>
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { gap: 3 },
  weekdayRow: { flexDirection: 'row', marginBottom: 2 },
  weekRow: { flexDirection: 'row', gap: 2 },
  cell: { flex: 1, aspectRatio: 1, alignItems: 'center', justifyContent: 'center', borderRadius: 3, borderWidth: 0.5 },
});
