import { useMemo, useState } from "react";
import { monthlyAssignmentTrend } from "./swiPersonalDashboardHelpers.js";
import "./swi-pd-embed.css";

export default function SwiAssignmentTrendWidget({ assignments = [] }) {
  const [active, setActive] = useState(null);
  const data = useMemo(() => monthlyAssignmentTrend(assignments), [assignments]);
  const max = Math.max(1, ...data.map((d) => d.count));

  return (
    <div className="swi-pd-widget swi-pd-trend">
      <div className="swi-pd-trend__bars">
        {data.map((item, index) => (
          <button
            key={item.key}
            type="button"
            className={`swi-pd-trend__col${active === index ? " is-active" : ""}`}
            onMouseEnter={() => setActive(index)}
            onMouseLeave={() => setActive(null)}
            onFocus={() => setActive(index)}
            onBlur={() => setActive(null)}
            aria-label={`${item.label}: ${item.count}`}
          >
            {active === index ? (
              <span className="swi-pd-trend__tip">{item.count}</span>
            ) : null}
            <span
              className="swi-pd-trend__bar"
              style={{ height: `${(item.count / max) * 100}%` }}
            />
            <span className="swi-pd-trend__label">{item.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}
