'use client';

import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
import {Tooltip} from '@astryxdesign/core/Tooltip';

export interface HeatCell {
  day: number; // 0 = Monday
  hour: number; // 0–23
  value: number;
}

const DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

/**
 * Peak Hours, deliberately NOT recharts.
 *
 * A 7×24 grid of divs tinted with color-mix() is smaller, faster and
 * monochrome by construction — recharts has no heatmap primitive, and building
 * one out of a scatter with custom shapes would be more code for a worse
 * result. Intensity is opacity against the top of the gray ramp.
 */
export function HeatmapGrid({
  data,
  hourLabels = [0, 6, 12, 18, 23],
}: {
  data: HeatCell[];
  hourLabels?: number[];
}) {
  const max = data.reduce((m, c) => Math.max(m, c.value), 0) || 1;
  const byKey = new Map(data.map((c) => [`${c.day}-${c.hour}`, c.value]));

  return (
    <VStack gap={1}>
      {DAYS.map((label, day) => (
        <HStack key={label} gap={1.5} vAlign="center">
          <HStack width={34}>
            <Text size="xsm" color="secondary">
              {label}
            </Text>
          </HStack>
          <HStack gap={0.5} width="100%">
            {Array.from({length: 24}, (_, hour) => {
              const value = byKey.get(`${day}-${hour}`) ?? 0;
              const pct = Math.round((value / max) * 100);
              return (
                <Tooltip
                  key={hour}
                  content={`${label} ${String(hour).padStart(2, '0')}:00 — ${value} visitors`}
                >
                  <span
                    style={{
                      flex: 1,
                      height: 18,
                      borderRadius: 3,
                      background: `color-mix(in oklab, var(--color-data-gray-5) ${pct}%, transparent)`,
                      boxShadow:
                        pct === 0
                          ? 'inset 0 0 0 1px var(--color-border)'
                          : undefined,
                    }}
                  />
                </Tooltip>
              );
            })}
          </HStack>
        </HStack>
      ))}
      <HStack gap={1.5} width="100%">
        {/* Spacer matching the day-label gutter, so the hour ticks line up
            with the columns rather than the row start. */}
        <HStack width={34} />
        <HStack gap={0.5} width="100%" hAlign="between">
          {hourLabels.map((h) => (
            <Text key={h} size="xsm" color="secondary">
              {String(h).padStart(2, '0')}:00
            </Text>
          ))}
        </HStack>
      </HStack>
    </VStack>
  );
}
