import { useEffect, useState } from "react";
import type { TransferRecord } from "../../store";
import { TransferRow } from "./TransferRow";
import { t } from "../../i18n";
import s from "./ActivityFeed.module.css";

export interface ActivityFeedProps
{
    active: TransferRecord[];
    history: TransferRecord[];
}

// 1Hz now tick：仅在有 active 时启动，避免空转。
function useNowTick(activeKey: string)
{
    const [ now, setNow ] = useState(() => Date.now());
    useEffect(() =>
    {
        if (!activeKey) { return; }
        const id = window.setInterval(() => setNow(Date.now()), 1000);
        return () => window.clearInterval(id);
    }, [ activeKey ]);
    return now;
}

export function ActivityFeed(props: ActivityFeedProps)
{
    const { active, history } = props;
    const activeKey = active.map((t) => t.sessionId).sort().join("|");
    const now = useNowTick(activeKey);

    if (active.length === 0 && history.length === 0) { return null; }

    return (
        <section className={s.section}>
            {active.length > 0 && (
                <div>
                    <div className={s.subhead}>{t("home.transfer.active")}</div>
                    <div className={s.list}>
                        {active.map((tr) => (
                            <TransferRow key={tr.sessionId} record={tr} active now={now} />
                        ))}
                    </div>
                </div>
            )}
            {history.length > 0 && (
                <div>
                    <div className={s.subhead}>{t("home.transfer.history")}</div>
                    <div className={s.list}>
                        {history.map((tr) => (
                            <TransferRow key={tr.sessionId} record={tr} active={false} now={now} />
                        ))}
                    </div>
                </div>
            )}
        </section>
    );
}
