import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useProjectStore = defineStore('project', () => {
  // --- STATE ---
  const projects = ref({
    'proj-1': {
      id: 'proj-1',
      name: 'My First Project',
      pages: {
        'page-0': {
          id: 'page-0',
          name: 'Page 0',
          components: [],
          width: 1280,
          height: 720,
          gridVisible: false,
          snapToGrid: false,
        }
      }
    }
  });

  const currentProjectId = ref(null);
  const activePageId = ref(null);
  const selectedComponentId = ref(null);
  const gridSize = ref(20); // A global grid size for now

  // --- GETTERS ---
  const currentProject = computed(() => {
    return currentProjectId.value ? projects.value[currentProjectId.value] : null;
  });

  const activePage = computed(() => {
    if (currentProject.value && activePageId.value) {
      return currentProject.value.pages[activePageId.value];
    }
    return null;
  });

  const activeComponents = computed(() => {
    return activePage.value ? activePage.value.components : [];
  });
  
  const selectedComponent = computed(() => {
    if (selectedComponentId.value && activePage.value) {
      return activePage.value.components.find(c => c.id === selectedComponentId.value);
    }
    return null;
  });

  // --- ACTIONS ---
  function createNewProject(name) {
    const newId = `proj-${Date.now()}`;
    projects.value[newId] = {
      id: newId,
      name: name,
      pages: {
        'page-0': {
          id: 'page-0',
          name: 'Page 0',
          components: [],
          width: 1280,
          height: 720,
          gridVisible: false,
          snapToGrid: false,
        }
      }
    };
    return newId;
  }
  
  function setCurrentProject(projectId) {
    currentProjectId.value = projectId;
    selectedComponentId.value = null; // Deselect component when changing project
    // Default to the first page when a project is opened
    if (currentProject.value) {
      activePageId.value = Object.keys(currentProject.value.pages)[0] || null;
    }
  }

  function addComponentToActivePage(payload) {
    if (activePage.value) {
      const { default: defaults, type, label } = payload.component;
      const defaultStyle = defaults?.style || {};
      const defaultProps = defaults?.props || {};

      // Try to parse percentage width/height for the editor state
      let width = 15;
      let height = 10;
      
      if (typeof defaultStyle.width === 'string' && defaultStyle.width.endsWith('%')) {
        width = parseFloat(defaultStyle.width);
      }
      if (typeof defaultStyle.height === 'string' && defaultStyle.height.endsWith('%')) {
        height = parseFloat(defaultStyle.height);
      }

      const newComponent = { 
        id: Date.now(),
        type,
        label,
        x: payload.x, // in percentage
        y: payload.y, // in percentage
        width,
        height,
        props: { ...defaultProps },
        style: { ...defaultStyle },
      };

      // Only add a 'text' property if it's a text-based component
      const textBasedTypes = ['h1', 'h2', 'p', 'a', 'button', 'input', 'textarea', 'password', 'search'];
      if (textBasedTypes.includes(type)) {
        newComponent.text = defaultProps.text || label || '';
      }

      activePage.value.components.push(newComponent);
    }
  }

  function updateComponentPosition(payload) {
    if (activePage.value) {
      const component = activePage.value.components.find(c => c.id === payload.id);
      if (component) {
        // Clamp values to keep component inside the artboard (0-100%)
        // We use a small buffer or allow exact 0-100.
        // Using Math.max/min prevents the "flying off screen" issue.
        component.x = Math.max(0, Math.min(100, payload.x));
        component.y = Math.max(0, Math.min(100, payload.y));
      }
    }
  }

  function updateComponentDimensions(payload) {
    if (activePage.value) {
      const component = activePage.value.components.find(c => c.id === payload.id);
      if (component) {
        component.width = payload.width;
        component.height = payload.height;
        // Also update the style to reflect the new dimensions so the visual element resizes
        component.style.width = `${payload.width}%`;
        component.style.height = `${payload.height}%`;
      }
    }
  }
  
  function setActivePage(pageId) {
    if (currentProject.value && currentProject.value.pages[pageId]) {
      activePageId.value = pageId;
      selectedComponentId.value = null; // Deselect component when changing page
    }
  }

  function setSelectedComponent(componentId) {
    selectedComponentId.value = componentId;
  }

  function createNewPage() {
    if (currentProject.value) {
      const pageName = `Page ${Object.keys(currentProject.value.pages).length}`;
      const newPageId = `page-${Date.now()}`;
      currentProject.value.pages[newPageId] = {
        id: newPageId,
        name: pageName,
        components: [],
        width: 1280,
        height: 720,
        gridVisible: false,
        snapToGrid: false,
      };
      setActivePage(newPageId);
    }
  }

  function updatePageDimensions({ width, height }) {
    if (activePage.value) {
      activePage.value.width = width;
      activePage.value.height = height;
    }
  }

  function toggleGrid() {
    if (activePage.value) {
      activePage.value.gridVisible = !activePage.value.gridVisible;
    }
  }

  function toggleSnap() {
    if (activePage.value) {
      activePage.value.snapToGrid = !activePage.value.snapToGrid;
    }
  }

  function updateComponentProperties(updatedComponent) {
    if (activePage.value) {
      const index = activePage.value.components.findIndex(c => c.id === updatedComponent.id);
      if (index !== -1) {
        const oldComponent = activePage.value.components[index];
        activePage.value.components[index] = { ...oldComponent, ...updatedComponent };
      }
    }
  }

  return { 
    projects,
    currentProjectId,
    activePageId,
    selectedComponentId,
    gridSize,
    currentProject,
    activePage,
    activeComponents,
    selectedComponent,
    createNewProject,
    setCurrentProject,
    setActivePage,
    setSelectedComponent,
    createNewPage,
    addComponentToActivePage,
    updateComponentPosition,
    updateComponentDimensions,
    updateComponentProperties,
    updatePageDimensions,
    toggleGrid,
    toggleSnap,
  }
})
