"use client";

import { useEffect, useRef } from "react";
import type { ScriptElementRow } from "@/lib/types";

export function ScriptElementTable({ elements, selectedId }: { elements: ScriptElementRow[]; selectedId?: number | string }) {
  const selected = useRef<HTMLTableRowElement>(null);
  useEffect(() => {
    if (typeof selected.current?.scrollIntoView === "function") selected.current.scrollIntoView({ block: "center" });
  }, [selectedId]);
  return <div className="elementTableViewport" tabIndex={0} aria-label="可滚动的脚本元素表">
    <table className="elementTable">
      <caption className="srOnly">完整脚本元素表</caption>
      <thead><tr><th>元素名称</th><th>一级维度</th><th>二级维度</th><th>使用段落</th></tr></thead>
      <tbody>{elements.map((element) => {
        const active = String(element.id) === String(selectedId);
        return <tr key={String(element.rowId)} ref={active ? selected : undefined} className={active ? "isSelected" : ""}>
          <th scope="row">{element.name}</th>
          <td>{element.primaryDimension || "—"}</td>
          <td>{element.secondaryDimension || "—"}</td>
          <td>{element.paragraphs.length ? <ul className="elementParagraphs">{element.paragraphs.map((paragraph) => <li key={String(paragraph.id)}><span>{paragraph.index ? `第 ${paragraph.index} 段` : "段落"}</span>{paragraph.name}</li>)}</ul> : <span className="emptyValue">未关联段落</span>}</td>
        </tr>;
      })}</tbody>
    </table>
  </div>;
}
