import type { RollResult } from "../types";
import styles from "./RollEntry.module.css";

interface RollEntryProps {
  roll: RollResult;
  fresh?: boolean;
}

function timeAgo(dateStr: string): string {
  const now = Date.now();
  const then = new Date(dateStr + "Z").getTime();
  const seconds = Math.floor((now - then) / 1000);
  if (seconds < 10) return "just now";
  if (seconds < 60) return `${seconds}s ago`;
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  return `${hours}h ago`;
}

export default function RollEntry({ roll, fresh }: RollEntryProps) {
  const { rolls, advantage, disadvantage, dice_expression } = roll;

  const isAdvantage = advantage && rolls.length === 2;
  const isDisadvantage = disadvantage && rolls.length === 2;
  const chosen = isAdvantage
    ? Math.max(...rolls)
    : isDisadvantage
      ? Math.min(...rolls)
      : null;
  const isNat20 = roll.nat20;

  return (
    <div
      className={`${styles.card} ${fresh ? styles.fresh : ""} ${isNat20 ? styles.nat20 : ""}`}
      style={{ borderLeftColor: roll.character_color || "#2a2a4a" }}
    >
      <div className={styles.topLine}>
        <span
          className={styles.charName}
          style={{ color: roll.character_color || "#c9a84c" }}
        >
          {roll.character_name}
        </span>
        <span className={styles.timestamp}>{timeAgo(roll.created_at)}</span>
      </div>
      <div className={styles.label}>
        {roll.label}
        {isAdvantage && <span className={styles.advantage}> ADV</span>}
        {isDisadvantage && <span className={styles.disadvantage}> DIS</span>}
      </div>
      {isNat20 && <div className={styles.critBanner}>NAT 20!</div>}
      <div className={styles.breakdown}>
        {dice_expression}: [
        {rolls.map((r, i) => (
          <span key={i}>
            {i > 0 && ", "}
            <span
              className={
                chosen === null
                  ? styles.dieResult
                  : r === chosen
                    ? styles.dieChosen
                    : styles.dieDiscarded
              }
            >
              {r}
            </span>
          </span>
        ))}
        ]{chosen !== null && ` → ${chosen}`}
      </div>
      {roll.modifier !== 0 && (
        <div className={styles.modLine}>
          {roll.modifier > 0 ? "+" : ""}
          {roll.modifier}
        </div>
      )}
      <div className={styles.total}>{roll.total}</div>
    </div>
  );
}
