import { useEffect, useLayoutEffect, useRef } from "react";
import clsx from "clsx";
import { Pin } from "lucide-react";
import { useAppStore } from "../../store/useAppStore";
import { setPinMode, setWindowSize, updatePinHotzone } from "../../api/tauri";
import styles from "./PinnedTasksOverlay.module.css";

const MIN_W = 200;
const MAX_W = 420;
const ROW_H = 28;
const CHROME_H = 44;

/**
 * 任务钉子模式：极透明浮层，只列出未完成任务；窗口默认点击穿透，
 * 鼠标移到钉子按钮上才可点击退出。
 */
export function PinnedTasksOverlay() {
  const tasks = useAppStore((s) => s.tasks);
  const toggleTaskPinMode = useAppStore((s) => s.toggleTaskPinMode);
  const rootRef = useRef<HTMLDivElement>(null);
  const pinRef = useRef<HTMLButtonElement>(null);

  const activeTasks = tasks
    .filter((t) => !t.done)
    .sort((a, b) => a.order - b.order);

  // 进入/退出时同步系统点击穿透与窗口尺寸
  useEffect(() => {
    document.documentElement.classList.add("task-pin-mode");
    void setPinMode(true);
    return () => {
      document.documentElement.classList.remove("task-pin-mode");
      void setPinMode(false);
      void updatePinHotzone(0, 0, 0, 0, false);
    };
  }, []);

  const syncLayout = () => {
    const root = rootRef.current;
    if (!root) return;
    const w = Math.min(MAX_W, Math.max(MIN_W, root.scrollWidth + 16));
    const h = CHROME_H + Math.max(activeTasks.length, 1) * ROW_H + 8;
    void setWindowSize(w, h);

    const pin = pinRef.current;
    if (pin) {
      const r = pin.getBoundingClientRect();
      void updatePinHotzone(r.left, r.top, r.width, r.height, true);
    }
  };

  useLayoutEffect(() => {
    syncLayout();
  }, [activeTasks.length, activeTasks.map((t) => t.title).join("|")]);

  useEffect(() => {
    const ro = new ResizeObserver(() => syncLayout());
    if (rootRef.current) ro.observe(rootRef.current);
    const t = window.setInterval(syncLayout, 500);
    return () => {
      ro.disconnect();
      window.clearInterval(t);
    };
  }, [activeTasks.length]);

  return (
    <div className={styles.root} ref={rootRef}>
      <div className={styles.header}>
        <button
          ref={pinRef}
          type="button"
          className={clsx(styles.pinBtn, styles.pinBtnActive)}
          title="取消钉子模式"
          onClick={() => toggleTaskPinMode()}
        >
          <Pin size={16} fill="currentColor" />
        </button>
        <span className={styles.label}>进行中 {activeTasks.length}</span>
      </div>

      <ul className={styles.list}>
        {activeTasks.length === 0 ? (
          <li className={styles.empty}>暂无未完成任务</li>
        ) : (
          activeTasks.map((t) => (
            <li key={t.id} className={styles.item}>
              <span className={styles.dot} />
              <span className={styles.title}>{t.title}</span>
            </li>
          ))
        )}
      </ul>
    </div>
  );
}
