import { useState } from 'react';

export type OpenFile = {
  path: string;
  name: string;
  content: string;
  originalContent: string;
  isDirty: boolean;
};

export const useEditorState = () => {
  const [files, setFiles] = useState<OpenFile[]>([]);
  const [activePath, setActivePath] = useState<string | null>(null);

  const openFile = (path: string, name: string, content: string) => {
    setFiles((prev) => {
      const existing = prev.find((f) => f.path === path);
      if (existing) return prev;
      return [...prev, { path, name, content, originalContent: content, isDirty: false }];
    });
    setActivePath(path);
  };

  const closeFile = (path: string) => {
    setFiles((prev) => {
      const next = prev.filter((f) => f.path !== path);
      if (activePath === path) {
        const idx = prev.findIndex((f) => f.path === path);
        const newActive = next[Math.min(idx, next.length - 1)] ?? null;
        setActivePath(newActive?.path ?? null);
      }
      return next;
    });
  };

  const setContent = (path: string, content: string) => {
    setFiles((prev) =>
      prev.map((f) => (f.path === path ? { ...f, content, isDirty: content !== f.originalContent } : f)),
    );
  };

  const markSaved = (path: string, content: string) => {
    setFiles((prev) =>
      prev.map((f) => (f.path === path ? { ...f, originalContent: content, content, isDirty: false } : f)),
    );
  };

  const getActiveFile = (): OpenFile | null => {
    return files.find((f) => f.path === activePath) ?? null;
  };

  return { files, activePath, setActivePath, openFile, closeFile, setContent, markSaved, getActiveFile };
};
