/**
 * @fileoverview Manages the user onboarding workflow, guiding them through
 * the initial setup of a design system project.
 */
import contextStore from '../stores/context-store.js';
import notificationService from '../services/notification-service.js';

const WORKFLOW_STEPS = [
  {
    id: 'create-project',
    title: 'Create a New Project',
    description: 'Projects are containers for your design system, linking your Figma files to your codebase.',
    action: { label: 'Go to Projects', event: 'onboarding:create-project' },
  },
  {
    id: 'configure-figma',
    title: 'Connect Figma File',
    description: 'Add your Figma file key to allow DSS to access your design tokens and components.',
    dependsOn: ['create-project'],
    action: { label: 'Configure Figma', event: 'onboarding:configure-figma' },
  },
  {
    id: 'extract-tokens',
    title: 'Extract Design Tokens',
    description: 'Scan your Figma file for variables and styles to generate design tokens.',
    dependsOn: ['configure-figma'],
    action: { label: 'Extract Tokens', event: 'onboarding:extract-tokens' },
  },
  {
    id: 'review-tokens',
    title: 'Review & Customize Tokens',
    description: 'Check the extracted tokens for accuracy before syncing them to your codebase.',
    dependsOn: ['extract-tokens'],
    optional: true,
    action: { label: 'Review Tokens', event: 'onboarding:review-tokens' },
  },
  {
    id: 'generate-components',
    title: 'Generate Components',
    description: 'Use the AI agent to generate initial component code from your design system.',
    dependsOn: ['extract-tokens'],
    action: { label: 'Go to Components', event: 'onboarding:generate-components' },
  },
  {
    id: 'setup-storybook',
    title: 'Set Up Storybook',
    description: 'View your generated components in an isolated Storybook environment.',
    dependsOn: ['generate-components'],
    optional: true,
    action: { label: 'Open Storybook', event: 'onboarding:setup-storybook' },
  },
];

/**
 * Initializes the onboarding workflow component with steps and event handlers.
 * @param {HTMLElement} workflowElement - The <ds-workflow> custom element.
 * @returns {Object} Object with destroy method for cleanup
 */
export function initOnboardingWorkflow(workflowElement) {
  if (!workflowElement || workflowElement.tagName !== 'DS-WORKFLOW') {
    console.error('Onboarding workflow requires a valid <ds-workflow> element.');
    return { destroy: () => {} };
  }

  workflowElement.steps = WORKFLOW_STEPS;
  workflowElement.setAttribute('workflow-id', 'onboarding');

  const handleAction = async (e) => {
    const { stepId } = e.detail;
    const project = contextStore.get('project');

    switch (e.type) {
      case 'onboarding:create-project':
        window.location.hash = 'projects';
        notificationService.create({
          title: 'Navigate to Projects',
          message: 'Create a new project from the projects page to continue.',
          type: 'info',
          source: 'Onboarding'
        });
        break;

      case 'onboarding:configure-figma':
        if (!project) {
          notificationService.create({
            title: 'No Project Selected',
            message: 'Please create and select a project first.',
            type: 'warning',
            source: 'Onboarding'
          });
          return;
        }
        window.location.hash = 'figma';
        workflowElement.updateStepStatus(stepId, 'completed');
        break;

      case 'onboarding:extract-tokens':
        window.location.hash = 'tokens';
        notificationService.create({
          title: 'Token Extraction',
          message: 'Use the Extract from Figma button to pull your design tokens.',
          type: 'info',
          source: 'Onboarding'
        });
        break;

      case 'onboarding:review-tokens':
        window.location.hash = 'tokens';
        workflowElement.updateStepStatus(stepId, 'completed');
        break;

      case 'onboarding:generate-components':
        window.location.hash = 'components';
        workflowElement.updateStepStatus(stepId, 'completed');
        break;

      case 'onboarding:setup-storybook':
        const storybookLink = document.getElementById('storybook-link');
        if (storybookLink) {
          window.open(storybookLink.href, '_blank');
        }
        workflowElement.updateStepStatus(stepId, 'completed');
        break;
    }
  };

  // Register event handlers
  WORKFLOW_STEPS.forEach(step => {
    if (step.action) {
      workflowElement.addEventListener(step.action.event, handleAction);
    }
  });

  // Listen for project changes to auto-complete first step
  const unsubscribe = contextStore.subscribeToKey('project', (newProject) => {
    if (newProject && workflowElement.steps[0].status !== 'completed') {
      workflowElement.updateStepStatus('create-project', 'completed');
    }
  });

  // Return cleanup function
  return {
    destroy: () => {
      WORKFLOW_STEPS.forEach(step => {
        if (step.action) {
          workflowElement.removeEventListener(step.action.event, handleAction);
        }
      });
      unsubscribe();
    }
  };
}

export { WORKFLOW_STEPS };
export default { initOnboardingWorkflow, WORKFLOW_STEPS };
