import { useRef } from "react";
import { useDetailsBackLayer } from "../../app/useBackLayer.js";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { useOutsideDismiss } from "../../shared/hooks/useOutsideDismiss.js";
import { CheckIcon, ImageUploadIcon, PlanIcon, PlusIcon, SkillIcon } from "../../shared/ActionIcons.jsx";

export function ComposerToolsMenu({ busy, uploadDisabled, fileRef, planMode, skills, selectedSkills, onOption, onToggleSkill }) {
  const { t } = useI18n();
  const menuRef = useRef(null);
  useDetailsBackLayer(menuRef, "tools-menu");
  const selected = new Set(selectedSkills.map((skill) => skill.name));
  const closeMenu = () => { if (menuRef.current?.open) menuRef.current.open = false; };
  useOutsideDismiss(menuRef, closeMenu);
  return <details className="composer-tools composer-menu" ref={menuRef}>
    <summary className="composer-icon-button" aria-label={t("composer.tools")}><span className="composer-plus-icon composer-action-icon" aria-hidden="true"><PlusIcon className="composer-action-svg" /></span></summary>
    <div className="composer-tools-panel wide-menu">
      <button type="button" className="tool-menu-row" disabled={uploadDisabled} onClick={() => { closeMenu(); fileRef.current?.click(); }}><span className="tool-icon"><ImageUploadIcon /></span><span><strong>{t("composer.uploadImage")}</strong></span></button>
      <button type="button" className={planMode ? "tool-menu-row selected" : "tool-menu-row"} disabled={busy} onClick={() => { onOption("planMode", !planMode); closeMenu(); }}><span className="tool-icon"><PlanIcon /></span><span><strong>{t("composer.planMode")}</strong></span>{planMode && <CheckIcon />}</button>
      {skills.length > 0 && <div className="tool-menu-section"><div className="popover-title">{t("composer.plugins")}</div>
        {skills.map((skill) => <button type="button" className={selected.has(skill.name) ? "tool-menu-row selected" : "tool-menu-row"} key={skill.name} disabled={busy} onClick={() => { onToggleSkill(skill); closeMenu(); }}>
          <span className="tool-icon"><SkillIcon /></span><span><strong>{skill.displayName || skill.name}</strong><small>{skill.description}</small></span>{selected.has(skill.name) && <CheckIcon />}
        </button>)}
      </div>}
    </div>
  </details>;
}
