"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanupDuplicateImports = cleanupDuplicateImports;
exports.initCommand = initCommand;
const inquirer_1 = __importDefault(require("inquirer"));
const chalk_1 = __importDefault(require("chalk"));
const ora_1 = __importDefault(require("ora"));
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const config_1 = require("../utils/config");
// Essential supporting files that components depend on
const ESSENTIAL_FILES = {
    'src/constants/tabs.ts': `export enum EFormBuilderTabs {
  BUILDER = 'builder',
  PREVIEW = 'preview'
}

export const TAB_CONFIG = {
  [EFormBuilderTabs.BUILDER]: {
    label: 'Form Builder',
    value: EFormBuilderTabs.BUILDER
  },
  [EFormBuilderTabs.PREVIEW]: {
    label: 'Form Preview', 
    value: EFormBuilderTabs.PREVIEW
  }
};`,
    'src/constants/formDefaults.ts': `export const DEFAULTS_SECTION_PROPERTIES = {
  backgroundColor: '#ffffff',
  padding: '16px',
  margin: '8px 0',
  borderRadius: '8px',
  border: '1px solid #e5e7eb'
};

export const HEADER_DEFAULTS = {
  title: 'Form Title',
  description: 'Form description',
  showLogo: false,
  logoAlignment: 'left'
};

export const VIEW_OPTIONS = [
  { label: 'Desktop', value: 'desktop' },
  { label: 'Tablet', value: 'tablet' },
  { label: 'Mobile', value: 'mobile' }
];

export const FORM_DEFAULTS = {
  title: 'New Form',
  description: 'Form description',
  theme: 'default'
};`,
    'src/constants/duplicateTypes.ts': `export enum EDuplicateMode {
  SECTION = 'section',
  FIELD = 'field'
}`,
    'src/constants/index.tsx': `export const DEFAULT_FORM_CONFIG = {
  id: 'default-form',
  title: 'New Form',
  description: 'Form description'
};

export const LAYOUT_TYPES = {
  SECTION: { TYPE: 'section' },
  DIVIDER: { TYPE: 'divider' },
  PAGE_BREAK: { TYPE: 'page_break' }
};

export const FIELD_TYPES = {
  TEXT: 'text',
  EMAIL: 'email',
  NUMBER: 'number',
  TEXTAREA: 'textarea',
  SELECT: 'select',
  CHECKBOX: 'checkbox',
  RADIO: 'radio',
  DATE: 'date',
  FILE: 'file',
  SIGNATURE: 'signature',
  PHONE: 'phone',
  URL: 'url'
};

// Export BOOLEAN_FIELD_OPTIONS from formDefaults
export { BOOLEAN_FIELD_OPTIONS, BOOLEAN_FIELD_OPTIONS_LEGACY, DIVIDER_DEFAULTS } from './formDefaults';`,
    'src/constants/elements.tsx': `import React from 'react';

export const FIELD_TYPES = {
  TEXT: 'text',
  EMAIL: 'email',
  NUMBER: 'number',
  TEXTAREA: 'textarea',
  SELECT: 'select',
  CHECKBOX: 'checkbox',
  RADIO: 'radio',
  DATE: 'date',
  FILE: 'file',
  SIGNATURE: 'signature',
  PHONE: 'phone',
  URL: 'url'
};

export const BOOLEAN_FIELD_OPTIONS = [
  { label: 'Yes', value: true },
  { label: 'No', value: false }
];

export const groupedFormElements = {
  'Basic Fields': [
    {
      type: 'field',
      fieldType: 'text',
      label: 'Text Input',
      icon: <div>T</div>,
      properties: { label: 'Text Field', placeholder: 'Enter text' }
    },
    {
      type: 'field',
      fieldType: 'email',
      label: 'Email',
      icon: <div>@</div>,
      properties: { label: 'Email Field', placeholder: 'Enter email' }
    },
    {
      type: 'field',
      fieldType: 'number',
      label: 'Number',
      icon: <div>#</div>,
      properties: { label: 'Number Field', placeholder: 'Enter number' }
    }
  ],
  'Layout': [
    {
      type: 'layout',
      layoutType: 'section',
      label: 'Section',
      icon: <div>□</div>,
      properties: { backgroundColor: '#ffffff', padding: '16px' }
    },
    {
      type: 'layout',
      layoutType: 'divider',
      label: 'Divider',
      icon: <div>—</div>,
      properties: { style: 'solid', color: '#e5e7eb' }
    }
  ]
};`,
    'src/constants/conditions.ts': `export const DEFAULT_MODAL_STATE = {
  isOpen: false,
  fieldId: null,
  conditions: []
};

export const CONDITION_OPERATORS = {
  EQUALS: 'equals',
  NOT_EQUALS: 'not_equals',
  CONTAINS: 'contains',
  NOT_CONTAINS: 'not_contains',
  GREATER_THAN: 'greater_than',
  LESS_THAN: 'less_than',
  IS_EMPTY: 'is_empty',
  IS_NOT_EMPTY: 'is_not_empty'
};

export const CONDITION_ACTIONS = {
  SHOW: 'show',
  HIDE: 'hide',
  ENABLE: 'enable',
  DISABLE: 'disable',
  REQUIRE: 'require',
  OPTIONAL: 'optional'
};`,
    'src/constants/keyboardKey.ts': `export const keyboardKeys = {
  ENTER: 'Enter',
  ESCAPE: 'Escape',
  TAB: 'Tab',
  SPACE: ' ',
  ARROW_UP: 'ArrowUp',
  ARROW_DOWN: 'ArrowDown',
  ARROW_LEFT: 'ArrowLeft',
  ARROW_RIGHT: 'ArrowRight'
};`,
    'src/constants/cssDefaults.ts': `export const CSS_DEFAULTS = {
  FORM_CONTAINER: {
    maxWidth: '800px',
    margin: '0 auto',
    padding: '2rem'
  },
  FIELD_SPACING: {
    marginBottom: '1.5rem'
  },
  BUTTON_STYLES: {
    padding: '0.75rem 1.5rem',
    borderRadius: '0.375rem',
    fontWeight: '500'
  }
};

export const STYLE_UTILS = {
  spacing: {
    xs: '0.25rem',
    sm: '0.5rem',
    md: '1rem',
    lg: '1.5rem',
    xl: '2rem'
  }
};

export const COLORS = {
  primary: '#3b82f6',
  secondary: '#64748b',
  success: '#10b981',
  warning: '#f59e0b',
  error: '#ef4444',
  background: '#ffffff',
  surface: '#f8fafc',
  text: '#1e293b'
};`,
    'src/constants/imageAlignmentOptions.tsx': `import React from 'react';
import { DIRECTIONS } from './directions';

export const LABEL_ALIGNMENT_KEYS = {
  LEFT: 'left',
  CENTER: 'center',
  RIGHT: 'right',
  LABEL: 'labelAlignment',
  FIELD: 'alignment'
};

export const LABEL_ALIGNMENT_OPTIONS = [
  { key: LABEL_ALIGNMENT_KEYS.LEFT, label: 'Left', value: 'left' },
  { key: LABEL_ALIGNMENT_KEYS.CENTER, label: 'Center', value: 'center' },
  { key: LABEL_ALIGNMENT_KEYS.RIGHT, label: 'Right', value: 'right' }
];

export const LOGO_ALIGNMENT_OPTIONS = [
  { key: 'left', label: 'Left', value: 'left' },
  { key: 'center', label: 'Center', value: 'center' },
  { key: 'right', label: 'Right', value: 'right' }
];

export const LOGO_SIZE_OPTIONS = [
  { value: '20%', label: '20%' },
  { value: '40%', label: '40%' },
  { value: '60%', label: '60%' },
  { value: '80%', label: '80%' },
  { value: '100%', label: '100%' }
];

export const IMAGE_ALIGNMENT_OPTIONS = [
  { value: DIRECTIONS.TOP_LEFT, position: 'items-start justify-start' },
  { value: DIRECTIONS.TOP_CENTER, position: 'items-start justify-center' },
  { value: DIRECTIONS.TOP_RIGHT, position: 'items-start justify-end' },
  { value: DIRECTIONS.CENTER_LEFT, position: 'items-center justify-start' },
  { value: DIRECTIONS.CENTER_CENTER, position: 'items-center justify-center' },
  { value: DIRECTIONS.CENTER_RIGHT, position: 'items-center justify-end' }
];

export const ALIGN_OPTIONS = [
  {
    id: DIRECTIONS.START,
    value: DIRECTIONS.START,
    icon: <div>←</div>
  },
  {
    id: DIRECTIONS.CENTER,
    value: DIRECTIONS.CENTER,
    icon: <div>↔</div>
  },
  {
    id: DIRECTIONS.END,
    value: DIRECTIONS.END,
    icon: <div>→</div>
  }
];

export type TLabelAlignmentKey = keyof typeof LABEL_ALIGNMENT_KEYS;
export type TLogoAlignmentValue = 'left' | 'center' | 'right';`,
    'src/constants/file.ts': `export const FILE_TYPES = {
  IMAGE: ['jpg', 'jpeg', 'png', 'gif', 'webp'],
  DOCUMENT: ['pdf', 'doc', 'docx', 'txt'],
  SPREADSHEET: ['xls', 'xlsx', 'csv'],
  ALL: ['*']
};

export const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
export const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE;

export const ACCEPTED_HEADER_LOGO_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
export const ALLOWED_IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
export const DEFAULT_MAX_FILE_SIZE = 10; // MB`,
    'src/constants/themeConstants.ts': `export enum EThemeCategory {
  COLORS = 'colors',
  TYPOGRAPHY = 'typography',
  SPACING = 'spacing',
  LAYOUT = 'layout'
}

export enum EButtonSize {
  SMALL = 'small',
  MEDIUM = 'medium',
  LARGE = 'large'
}

export const DEFAULT_THEME = {
  colors: {
    primary: '#3b82f6',
    secondary: '#64748b',
    success: '#10b981',
    warning: '#f59e0b',
    error: '#ef4444',
    background: '#ffffff',
    surface: '#f8fafc',
    text: '#1e293b'
  },
  fonts: {
    primary: 'Inter, sans-serif',
    secondary: 'system-ui, sans-serif'
  },
  spacing: {
    xs: '0.25rem',
    sm: '0.5rem',
    md: '1rem',
    lg: '1.5rem',
    xl: '2rem'
  }
};`,
    'src/constants/fonts.ts': `export const FONT_FAMILIES = [
  { label: 'Inter', value: 'Inter, sans-serif' },
  { label: 'Roboto', value: 'Roboto, sans-serif' },
  { label: 'Open Sans', value: 'Open Sans, sans-serif' },
  { label: 'Lato', value: 'Lato, sans-serif' },
  { label: 'Montserrat', value: 'Montserrat, sans-serif' },
  { label: 'Poppins', value: 'Poppins, sans-serif' }
];

export const FONT_SIZES = [
  { label: 'Small', value: '14px' },
  { label: 'Medium', value: '16px' },
  { label: 'Large', value: '18px' },
  { label: 'Extra Large', value: '20px' }
];

export const FONT_SIZE_OPTIONS = FONT_SIZES;
export const FONTS = FONT_FAMILIES;`,
    'src/constants/themeCategories.tsx': `import React from 'react';

export const THEME_CATEGORIES = [
  {
    id: 'colors',
    label: 'Colors',
    icon: <div className="w-4 h-4 bg-blue-500 rounded"></div>
  },
  {
    id: 'typography',
    label: 'Typography',
    icon: <div className="w-4 h-4 text-gray-600">Aa</div>
  },
  {
    id: 'spacing',
    label: 'Spacing',
    icon: <div className="w-4 h-4 border border-gray-400"></div>
  }
];

export default THEME_CATEGORIES;`,
    'src/constants/predefinedThemes.ts': `export const PREDEFINED_THEMES = [
  {
    id: 'default',
    name: 'Default',
    colors: {
      primary: '#3b82f6',
      secondary: '#64748b',
      background: '#ffffff'
    }
  },
  {
    id: 'dark',
    name: 'Dark',
    colors: {
      primary: '#60a5fa',
      secondary: '#94a3b8',
      background: '#1e293b'
    }
  }
];`,
    'src/constants/themeUtils.ts': `export function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

export function rgbToHex(r: number, g: number, b: number): string {
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

export function applyThemeFixes(theme: any) {
  // Apply theme fixes and transformations
  return theme;
}`,
    'src/constants/labelAlignment.ts': `const LABEL_ALIGNMENT_CONSTANTS = {
  LEFT: 'left',
  CENTER: 'center',
  RIGHT: 'right'
};

export default LABEL_ALIGNMENT_CONSTANTS;`,
    'src/constants/formCanvasTypes.ts': `export enum EFormCanvasType {
  DESKTOP = 'desktop',
  MOBILE = 'mobile',
  TABLET = 'tablet'
}`,
    'src/constants/directions.ts': `export const DIRECTIONS = {
  LEFT: 'left',
  RIGHT: 'right',
  TOP: 'top',
  BOTTOM: 'bottom',
  CENTER: 'center',
  TOP_LEFT: 'top-left',
  TOP_CENTER: 'top-center',
  TOP_RIGHT: 'top-right',
  BOTTOM_LEFT: 'bottom-left',
  BOTTOM_CENTER: 'bottom-center',
  BOTTOM_RIGHT: 'bottom-right',
  CENTER_LEFT: 'center-left',
  CENTER_RIGHT: 'center-right',
  CENTER_CENTER: 'center-center',
  START: 'start',
  END: 'end'
};

export const ALIGNMENTS = {
  LEFT: 'left',
  CENTER: 'center',
  RIGHT: 'right',
  JUSTIFY: 'justify'
};`,
    'src/utils/helperFunctions.ts': `export function cleanFormConfig(config: any) {
  // Clean form configuration
  return config;
}

export function enrichFormConfig(config: any) {
  // Enrich form configuration
  return config;
}

export function isElementLayout(element: any): boolean {
  return element?.type === 'layout';
}

export function getLabelAlignmentClass(alignment: string): string {
  const alignmentMap: Record<string, string> = {
    left: 'text-left',
    center: 'text-center',
    right: 'text-right'
  };
  return alignmentMap[alignment] || 'text-left';
}

export function transformFormData(data: any) {
  // Transform form data for submission
  return data;
}

export function toBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = error => reject(error);
  });
}

export function simulateProgress(callback: (progress: number) => void) {
  let progress = 0;
  const interval = setInterval(() => {
    progress += 10;
    callback(progress);
    if (progress >= 100) {
      clearInterval(interval);
    }
  }, 100);
}`,
    'src/utils/logoAlignmentRenderer.tsx': `import React from 'react';

export function renderLogoAlignment(alignment: string) {
  return <div className={\`logo-\${alignment}\`}>Logo</div>;
}

export type TLogoAlignmentValue = 'left' | 'center' | 'right';`,
    'src/utils/conditionEngine.ts': `export interface IConditionRule {
  id: string;
  fieldId: string;
  operator: string;
  value: any;
  action: string;
}

export function evaluateCondition(condition: IConditionRule, formData: any): boolean {
  const fieldValue = formData[condition.fieldId];
  
  switch (condition.operator) {
    case 'equals':
      return fieldValue === condition.value;
    case 'not_equals':
      return fieldValue !== condition.value;
    case 'contains':
      return String(fieldValue).includes(condition.value);
    case 'not_contains':
      return !String(fieldValue).includes(condition.value);
    case 'greater_than':
      return Number(fieldValue) > Number(condition.value);
    case 'less_than':
      return Number(fieldValue) < Number(condition.value);
    case 'is_empty':
      return !fieldValue || fieldValue === '';
    case 'is_not_empty':
      return fieldValue && fieldValue !== '';
    default:
      return false;
  }
}`,
    'src/lib/utils.ts': `import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

export function generateId(): string {
  return Math.random().toString(36).substr(2, 9);
}

export function generateIdWithPrefix(prefix: string): string {
  return \`\${prefix}_\${generateId()}\`;
}`,
    'src/utils/cn.ts': `import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}`,
    'src/utils/idGenerator.ts': `export function generateId(): string {
  return Math.random().toString(36).substr(2, 9);
}

export function generateIdWithPrefix(prefix: string): string {
  return \`\${prefix}_\${generateId()}\`;
}`,
    'src/utils/timeUtils.ts': `export function parseTimeStringToDate(timeString: string): Date {
  const [hours, minutes] = timeString.split(':').map(Number);
  const date = new Date();
  date.setHours(hours, minutes, 0, 0);
  return date;
}

export function formatDateToTimeString(date: Date): string {
  return date.toTimeString().slice(0, 5);
}

export function getTimeFormat(): string {
  return 'HH:mm';
}

export function formatTime(date: Date): string {
  return date.toLocaleTimeString('en-US', {
    hour12: false,
    hour: '2-digit',
    minute: '2-digit'
  });
}

export function parseTime(timeString: string): Date | null {
  try {
    return parseTimeStringToDate(timeString);
  } catch {
    return null;
  }
}

export function isValidTimeString(timeString: string): boolean {
  const timeRegex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;
  return timeRegex.test(timeString);
}

export function addMinutes(date: Date, minutes: number): Date {
  const result = new Date(date);
  result.setMinutes(result.getMinutes() + minutes);
  return result;
}

export function subtractMinutes(date: Date, minutes: number): Date {
  const result = new Date(date);
  result.setMinutes(result.getMinutes() - minutes);
  return result;
}

export function getTimeDifference(startTime: Date, endTime: Date): number {
  return endTime.getTime() - startTime.getTime();
}

export function formatDuration(milliseconds: number): string {
  const minutes = Math.floor(milliseconds / 60000);
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  
  if (hours > 0) {
    return \`\${hours}h \${remainingMinutes}m\`;
  }
  return \`\${remainingMinutes}m\`;
}`,
    'src/utils/index.tsx': `export { generateId, generateIdWithPrefix } from './idGenerator';
export { cn } from './cn';
export * from './helperFunctions';
export * from './formConfigParser';
export * from './timeUtils';`,
    'src/hooks/useFormConditions.ts': `import { useState, useCallback } from 'react';

export function useFormConditions() {
  const [conditions, setConditions] = useState<any[]>([]);

  const addCondition = useCallback((condition: any) => {
    setConditions(prev => [...prev, condition]);
  }, []);

  const removeCondition = useCallback((conditionId: string) => {
    setConditions(prev => prev.filter(c => c.id !== conditionId));
  }, []);

  const updateCondition = useCallback((conditionId: string, updates: any) => {
    setConditions(prev => prev.map(c => c.id === conditionId ? { ...c, ...updates } : c));
  }, []);

  return {
    conditions,
    addCondition,
    removeCondition,
    updateCondition
  };
}`,
    'src/hooks/useThemeStyles.ts': `import { useState, useCallback } from 'react';

export function useThemeStyles() {
  const [theme, setTheme] = useState<any>({});

  const updateTheme = useCallback((updates: any) => {
    setTheme(prev => ({ ...prev, ...updates }));
  }, []);

  const resetTheme = useCallback(() => {
    setTheme({});
  }, []);

  return {
    theme,
    updateTheme,
    resetTheme
  };
}`,
    'src/mocks/index.ts': `export const defaultForm = {
  id: 'default-form',
  title: 'Sample Form',
  description: 'This is a sample form',
  pages: [
    {
      id: 'page-1',
      pageNumber: 1,
      title: 'Page 1',
      sections: []
    }
  ]
};`,
    'src/types.d.ts': `export interface IFormConfig {
  id: string;
  title: string;
  description: string;
}

export interface IFormField {
  id: string;
  type: string;
  properties: any;
  validations?: any;
  conditions?: any;
  sectionId: string;
}

export interface ILayoutContainer {
  id: string;
  type: string;
  properties: any;
  fields?: IFormField[];
}

export interface IFormPages {
  id: string;
  pageNumber: number;
  title: string;
  sections: ILayoutContainer[];
}

export interface IFormHeader {
  title: string;
  description: string;
  showLogo: boolean;
  logoAlignment: string;
}

export interface IDragItem {
  type: string;
  fieldType?: string;
  layoutType?: string;
  properties?: any;
  validations?: any;
  conditions?: any;
}

export type TSelectedElement = {
  type: 'field' | 'layout' | 'header' | 'page';
  element: any;
} | null;

export interface IThemeConfig {
  id: string;
  name: string;
  colors: Record<string, string>;
  fonts: Record<string, string>;
  spacing: Record<string, string>;
}

export interface ICondition {
  id: string;
  fieldId: string;
  operator: string;
  value: any;
  action: string;
}

export interface IThemeSettings {
  colors: Record<string, string>;
  fonts: Record<string, string>;
  spacing: Record<string, string>;
}

export type TThemeUpdateFunction = (updates: Partial<IThemeSettings>) => void;`,
    'src/assets/svgIcons/icons.tsx': `import React from 'react';

export const addIcon = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8 2a1 1 0 0 1 1 1v4h4a1 1 0 1 1 0 2H9v4a1 1 0 1 1-2 0V9H3a1 1 0 0 1 0-2h4V3a1 1 0 0 1 1-1z"/></svg>;

export const duplicate = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M4 2a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H4z"/></svg>;

export const grip = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M10 13a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM10 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM10 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM6 13a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM6 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM6 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/></svg>;

export const conditions = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2z"/></svg>;

export const play = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/></svg>;

export const PreviewIcon = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM1.173 8a13.133 13.133 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.133 13.133 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5c-2.12 0-3.879-1.168-5.168-2.457A13.134 13.134 0 0 1 1.172 8z"/></svg>;

export const AlignLeft = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M2 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5zm0-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>;

export const AlignRight = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M6 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-4-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5zm4-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-4-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>;

export const phone = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M11 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h6zM5 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H5z"/></svg>;

export const tablet = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M12 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h8zM4 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H4z"/></svg>;

export const desktop = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M0 4s0-2 2-2h12s2 0 2 2v6s0 2-2 2h-4c0 .667.083 1.167.25 1.5H11a.5.5 0 0 1 0 1H5a.5.5 0 0 1 0-1h.75c.167-.333.25-.833.25-1.5H2s-2 0-2-2V4zm1.398-.855a.758.758 0 0 0-.254.302A1.46 1.46 0 0 0 1 4.01V10c0 .325.078.502.145.602.07.105.17.188.302.254a1.464 1.464 0 0 0 .538.143L2.01 11H14c.325 0 .502-.078.602-.145a.758.758 0 0 0 .254-.302 1.464 1.464 0 0 0 .143-.538L15 9.99V4c0-.325-.078-.502-.145-.602a.757.757 0 0 0-.302-.254A1.46 1.46 0 0 0 13.99 3H2c-.325 0-.502.078-.602.145z"/></svg>;

export const MinusIcon = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M4 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 4 8z"/></svg>;

export const PlusIcon = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/></svg>;

export const AlignCenter = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M6 12.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5zm2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5z"/></svg>;

export const BoldImg = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8.21 13c2.106 0 3.412-1.087 3.412-2.823 0-1.306-.984-2.283-2.324-2.386v-.055a2.176 2.176 0 0 0 1.852-2.14c0-1.51-1.162-2.46-3.014-2.46H3.843V13H8.21zM5.908 4.674h1.696c.963 0 1.517.451 1.517 1.244 0 .834-.629 1.32-1.73 1.32H5.908V4.673zm0 6.788V8.598h1.73c1.217 0 1.88.492 1.88 1.415 0 .943-.643 1.449-1.832 1.449H5.907z"/></svg>;

export const ItalicImg = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M7.991 11.674 9.53 4.455c.123-.595.246-.71 1.347-.807l.11-.52H7.211l-.11.52c1.06.096 1.128.212 1.005.807L6.57 11.674c-.123.595-.246.71-1.346.806l-.11.521h3.774l.11-.521c-1.06-.095-1.129-.211-1.006-.806z"/></svg>;

export const tickIcon = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M10.97 4.97a.235.235 0 0 0-.02.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.061L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-1.071-1.05z"/></svg>;

// Simple deleteIcon using X symbol
export const deleteIcon = <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/></svg>;`,
    'src/assets/images/copy.png': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADgAAAA5CAYAAABj2ui7AAAACXBIWXMAACxLAAAsSwGlPZapAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAV2SURBVHgB7VpdUuNGEO4eSYYiL+QEES9b8SapwAnWnCD4BJgTxFsLVN4wbymzVcAJMCeAnABzAtgKwam8oJwg5GlZGau3W7LBxjOSLUuGde1XBYaZ8Xg+9/z0940AvuLLBsJzonqx6DjOGoL1BoCWAXGRS92+Fh4ReACdD0R0ev/+pyaMiWchaG/+WUK0dxChBONBCDfbbdiFg6I3yhumSlCIKWUfwWCUUiEAPLj3PzLRldu4dtMhWG25jgNHKSKWBI5op9ze+/HS1EBBzpCoFQpwlgM5gYtoXTib11VTg1wJOu9a6zwlzyCDKRkHVLhvb7Z2dHW5ERRyaEEjqR0B3iJ1DvmvslKw5NeLKD8L/t23RNYKbyobCHSe1A+/t6aLZC5rcERyHpN669dfn8IImP+t5QYB1XjI63HtggBW798Xm73/MydYeHe9BhaexLXhM+2wvfe6CingbLUqvJ5lOrqGJp7v3630dtfsp6ildkxVMh15Kq2mJSdo7xUb0geEM0AL1y4UHvrPnCDFfLNAavXu98fpkxbchyck5QvT1SPhr5Ilyd+ZE1REujPJiyL36hIygpC0Airr6pBTvl4UMyfIm8sGDE6fkJwMCDLGXbiZoHaTCqMIOWYyvOuVeNdbXPA/NW8T0qkJP4d3V7jR1cmO+rxqIiPMbbXOSJMpcRp3mHuqNg0ESH/oyhHQnQmCQEFTW47q55kg2G5/4xmqZiSCB0vGTWw2CMbATmoQ5ZaSftFy1y7YGNUuSPxwljgsdcIDmTOgxn39+7eQAs7W1bKunHPe29gIiiqIEmcKOxDRKuK1lwZNAk6aj0TisBRalB8FVLW3/6pBCiAqV18BH4wEYySPaxXmSjABhBx/WZWn5b3sY1xQAGu6ck7ZbrQERxWraWAiNwl4mr/RlTPx82GCW/8sJ5DzOpx+QQqMQO4Yxu7zqgIGBWNZ0BwkyO5XATtxYjVMnCFFbplEjjeZ4zQ6kU2nHX1/dB7KqoFB2GIJmPVcWlUwErl6sQJjohAZTa6+U2zICz4O4oqtAOtI25aFpaVo5SWR65rIZ4Zqj42rpbBdr8QUagGTK78kcrKUeGM5CXvQ9Ets7XdhRwMxL9QAYNdPYTPkSS48i/ns1NYjNLjfRu9fFf2yTFacd18v1mBM5E8uZp/Ax+gJbHkTGWz1/lCPCmf7733OTCqm+tTkGAnkeLwWL6VXXn+ZcpxOydDeE4sOxkfFVDEJuXneVCCWHGzoTC1OAVVJ+w6EJqQAUvC/rnwSchHMuiAipw+GUojf6So6pLcBEoHUeFo0ObmegzZs9saRE6gAUSs1FAUepIBf/6HGL7J2va4xuzspuYcxhY42HUf9sv/aoXLSMsLCdov0Ay3OhOM284reTDADUfsSwLso/aurcBzHhRmARFB/IWI6Pr4wKDLdsyH+AjMAZZHhdkbSN07jIE/Ik07siNlRlpILwqOA88f/UJud0ynfoZchDwwnznz1LG5Bttds4S6KIE856IBr7F2WIGvoVYHLeXHqq20TQoK+v3BgaoBIJ5lOVTa1TKqARXfm6z46B0NvP9BKI7kOjszeyUnKWnMwMEoeNooyvyh9OOi7UfQM7cIp1VX+qSA2vXgoaFLiDOyMrz+TMJBvzvN6CxScxb2Bs/fGOI8zFrb5bgNwHxIe50pSBWkxlFDPbV5XSYUDgoQBNVlUiVF72W63vZ5XOl+9cANrbplUUAK01+Mi1tdXLuQEWsXACqPGLzswBeRJTqBNtv3IaMp8PTxB99mZ/MgJYjWfI/cUkZXvQqYfSufsa1byeHZm+LOSUL1ZdJyPNT4uUl1tPYFEbSOLx7lGxciqve9xRrmqcmEMdCNWmyaxHj4D',
    'src/assets/images/Cloudwick.png': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
    'src/assets/images/group.png': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
    'src/utils/formConfigParser.ts': `import { z } from 'zod';

export function createFieldZodSchema(field: any): z.ZodSchema {
  let schema: z.ZodSchema = z.any();

  switch (field.fieldType || field.type) {
    case 'text':
    case 'textarea':
      schema = z.string();
      break;
    case 'email':
      schema = z.string().email();
      break;
    case 'number':
      schema = z.number();
      break;
    case 'date':
      schema = z.date();
      break;
    case 'boolean':
    case 'checkbox':
      schema = z.boolean();
      break;
    case 'select':
    case 'radio':
      schema = z.string();
      break;
    case 'file':
      schema = z.any();
      break;
    default:
      schema = z.any();
  }

  // Apply validation rules
  if (field.validations) {
    if (field.validations.required) {
      // Schema is already required by default
    }
    if (field.validations.minLength && typeof schema._def.innerType === 'undefined') {
      schema = (schema as z.ZodString).min(field.validations.minLength);
    }
    if (field.validations.maxLength && typeof schema._def.innerType === 'undefined') {
      schema = (schema as z.ZodString).max(field.validations.maxLength);
    }
  }

  return field.validations?.required !== false ? schema : schema.optional();
}

export function parseTimeStringToDate(timeString: string): Date {
  const [hours, minutes] = timeString.split(':').map(Number);
  const date = new Date();
  date.setHours(hours, minutes, 0, 0);
  return date;
}

export function formatDateToTimeString(date: Date): string {
  return date.toTimeString().slice(0, 5);
}

export function validateFormData(formData: any, schema: z.ZodSchema): { success: boolean; errors?: any } {
  try {
    schema.parse(formData);
    return { success: true };
  } catch (error) {
    if (error instanceof z.ZodError) {
      return { success: false, errors: error.errors };
    }
    return { success: false, errors: [{ message: 'Validation failed' }] };
  }
}

export function createFormSchema(fields: any[]): z.ZodSchema {
  const schemaObject: Record<string, z.ZodSchema> = {};
  
  fields.forEach(field => {
    if (field.id) {
      schemaObject[field.id] = createFieldZodSchema(field);
    }
  });
  
  return z.object(schemaObject);
}`
};
async function createEssentialFiles(cwd, config) {
    // Note: Essential files from registry should NOT be created during init
    // They will be created automatically when components are added under the component's basePath
    // This ensures all files go to the correct location based on the user's basePath setting
    // and prevents creating folders with alias names at the root or in wrong locations
}
async function addCombinedCssImport(cwd) {
    const mainFiles = ['src/main.tsx', 'src/main.jsx'];
    // Get the config to determine the basePath
    const config = await (0, config_1.getConfig)(cwd);
    const basePath = config?.basePath || 'src/';
    // Ensure basePath ends with /
    const normalizedBasePath = basePath.endsWith('/') ? basePath : basePath + '/';
    // Calculate the relative path from src/ to the assets/css/combined.css
    const relativeCssPath = path_1.default.relative('src/', path_1.default.join(normalizedBasePath, 'assets/css/combined.css')).replace(/\\/g, '/');
    const cssImportPath = relativeCssPath.startsWith('.') ? relativeCssPath : `./${relativeCssPath}`;
    for (const mainFile of mainFiles) {
        const mainPath = path_1.default.resolve(cwd, mainFile);
        if (await fs_extra_1.default.pathExists(mainPath)) {
            const content = await fs_extra_1.default.readFile(mainPath, 'utf8');
            // Check if any CSS import already exists (with any path - ./assets/css/combined.css, ../lib/assets/css/combined.css, etc.)
            const existingCssImportPattern = /import\s+["'][^"']*\/assets\/css\/combined\.css["'];?/;
            if (!existingCssImportPattern.test(content)) {
                // Add the import at the top of the file, after other imports
                const lines = content.split('\n');
                let insertIndex = 0;
                // Find the best place to insert - after other local CSS imports but before Astral UI imports
                let lastLocalCssIndex = -1;
                let astralUIImportIndex = -1;
                for (let i = 0; i < lines.length; i++) {
                    const line = lines[i].trim();
                    // Check for Astral UI imports
                    if (line.includes('@cloudwick/astral-ui')) {
                        astralUIImportIndex = i;
                        break;
                    }
                    // Check for local CSS imports
                    if (line.startsWith('import ') &&
                        (line.includes("'./") || line.includes('"./'))) {
                        if (line.includes('.css')) {
                            lastLocalCssIndex = i;
                        }
                    }
                }
                // Determine insertion point
                if (astralUIImportIndex !== -1) {
                    // Insert before Astral UI imports
                    insertIndex = astralUIImportIndex;
                }
                else if (lastLocalCssIndex !== -1) {
                    // Insert after other local CSS imports
                    insertIndex = lastLocalCssIndex + 1;
                }
                else {
                    // Fallback: find the last import statement
                    for (let i = 0; i < lines.length; i++) {
                        if (lines[i].trim().startsWith('import ') && !lines[i].includes('//')) {
                            insertIndex = i + 1;
                        }
                    }
                }
                // Insert the CSS import with dynamic path
                lines.splice(insertIndex, 0, `import "${cssImportPath}";`);
                const updatedContent = lines.join('\n');
                await fs_extra_1.default.writeFile(mainPath, updatedContent);
                console.log(chalk_1.default.green(`✓ Added combined.css import to ${mainFile}: ${cssImportPath}`));
                return;
            }
            else {
                console.log(chalk_1.default.yellow(`ℹ combined.css import already exists in ${mainFile}`));
                return;
            }
        }
    }
    console.log(chalk_1.default.yellow('ℹ No main.tsx or main.jsx file found to add CSS import'));
}
async function setupTailwindConfig(cwd) {
    const tailwindConfigPath = path_1.default.resolve(cwd, 'tailwind.config.js');
    const tailwindConfigTsPath = path_1.default.resolve(cwd, 'tailwind.config.ts');
    let configExists = false;
    let configFile = '';
    if (await fs_extra_1.default.pathExists(tailwindConfigTsPath)) {
        configExists = true;
        configFile = tailwindConfigTsPath;
    }
    else if (await fs_extra_1.default.pathExists(tailwindConfigPath)) {
        configExists = true;
        configFile = tailwindConfigPath;
    }
    if (!configExists) {
        console.log(chalk_1.default.yellow('⚠️ No tailwind.config.js found.'));
        console.log(chalk_1.default.cyan('📦 Please create a Tailwind config file:'));
        console.log(chalk_1.default.white('   npx tailwindcss init'));
        return;
    }
    try {
        const configContent = await fs_extra_1.default.readFile(configFile, 'utf-8');
        // Check if content paths include src directory
        if (!configContent.includes('./src/**/*.{js,ts,jsx,tsx}')) {
            console.log(chalk_1.default.yellow('⚠️ Tailwind config may need to include src directory in content paths.'));
            console.log(chalk_1.default.cyan('💡 Make sure your tailwind.config.js includes:'));
            console.log(chalk_1.default.white('   content: ["./src/**/*.{js,ts,jsx,tsx}"]'));
        }
        console.log(chalk_1.default.green('✓ Tailwind configuration found'));
    }
    catch (error) {
        console.log(chalk_1.default.yellow('⚠️ Could not read Tailwind configuration file.'));
    }
}
async function setupProjectAliases(cwd, config) {
    // Setup Vite config aliases
    const viteConfigPath = path_1.default.resolve(cwd, 'vite.config.js');
    const viteConfigTsPath = path_1.default.resolve(cwd, 'vite.config.ts');
    let viteConfigExists = false;
    let viteConfigFile = '';
    let isTypeScript = false;
    let isESModule = false;
    if (await fs_extra_1.default.pathExists(viteConfigTsPath)) {
        viteConfigExists = true;
        viteConfigFile = viteConfigTsPath;
        isTypeScript = true;
    }
    else if (await fs_extra_1.default.pathExists(viteConfigPath)) {
        viteConfigExists = true;
        viteConfigFile = viteConfigPath;
    }
    // Check if project uses ES modules
    const packageJsonPath = path_1.default.resolve(cwd, 'package.json');
    if (await fs_extra_1.default.pathExists(packageJsonPath)) {
        try {
            const packageJson = await fs_extra_1.default.readJson(packageJsonPath);
            isESModule = packageJson.type === 'module';
        }
        catch {
            // Ignore errors
        }
    }
    if (viteConfigExists) {
        try {
            const viteConfig = await fs_extra_1.default.readFile(viteConfigFile, 'utf-8');
            // Determine base path for formbuilder (e.g., src/formbuilder)
            const basePath = config.basePath || 'src/';
            const formbuilderBasePath = basePath.replace(/\/$/, '') + '/formbuilder';
            // Get user-specified paths - #formickComponents should point to base formbuilder directory
            const componentsPath = formbuilderBasePath.replace(/\/$/, '');
            const utilsPath = (config.aliases.utils.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/utils`).replace(/\/$/, '');
            const constantsPath = (config.aliases.constants.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/constants`).replace(/\/$/, '');
            const typesPath = (config.aliases.types.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/types`).replace(/\/$/, '');
            const hooksPath = (config.aliases.hooks.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/hooks`).replace(/\/$/, '');
            const assetsPath = (config.aliases.assets.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/assets`).replace(/\/$/, '');
            const mocksPath = (config.aliases.mocks.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/mocks`).replace(/\/$/, '');
            // Check if formick aliases need to be added or updated
            const needsUpdate = !viteConfig.includes('#formickComponents') ||
                (viteConfig.includes('#formickComponents') && !viteConfig.includes(`'${componentsPath}'`) && !viteConfig.includes(`"${componentsPath}"`));
            if (needsUpdate) {
                let updatedConfig = viteConfig;
                // Determine __dirname syntax based on ES module
                const dirnameSyntax = isESModule
                    ? "path.dirname(fileURLToPath(import.meta.url))"
                    : "__dirname";
                // Add necessary imports for ES modules
                if (isESModule && !viteConfig.includes('fileURLToPath')) {
                    if (!viteConfig.includes('import path from')) {
                        updatedConfig = updatedConfig.replace(/import\s+{[^}]+}\s+from\s+['"]vite['"];?/, (match) => `import path from 'path';\nimport { fileURLToPath } from 'url';\n${match}`);
                    }
                    else if (!viteConfig.includes('from \'url\'')) {
                        updatedConfig = updatedConfig.replace(/import\s+path\s+from\s+['"]path['"];?/, (match) => `${match}\nimport { fileURLToPath } from 'url';`);
                    }
                    // Add __dirname constant if not present
                    if (!viteConfig.includes('const __dirname')) {
                        const importMatch = updatedConfig.match(/import\s+{[^}]+}\s+from\s+['"]url['"];?/);
                        if (importMatch) {
                            updatedConfig = updatedConfig.replace(importMatch[0], `${importMatch[0]}\n\nconst __dirname = ${dirnameSyntax};`);
                        }
                    }
                }
                else if (!isESModule && !viteConfig.includes('import path from')) {
                    // Add path import for CommonJS
                    updatedConfig = updatedConfig.replace(/import\s+{[^}]+}\s+from\s+['"]vite['"];?/, (match) => `import path from 'path';\n${match}`);
                }
                // Clean up broken alias entries first - remove lines that are incomplete
                updatedConfig = updatedConfig.replace(/\s+['"][^'"]*['"]\s*\),?\s*\n/g, '');
                updatedConfig = updatedConfig.replace(/\s+path\.resolve\([^)]+\),\s*\n/g, '');
                updatedConfig = updatedConfig.replace(/\s+['"]#formick\w+['"]\s*:\s*path\.resolve\([^)]*$/gm, '');
                // Check if resolve.alias already exists
                const aliasBlockMatch = updatedConfig.match(/(alias:\s*\{)([\s\S]*?)(\n\s*\},?\s*\n\s*\})/);
                if (aliasBlockMatch) {
                    const [, aliasStart, aliasContent, closingBrace] = aliasBlockMatch;
                    // Clean up any broken entries in aliasContent
                    let cleanedContent = aliasContent
                        .replace(/\s+['"][^'"]*['"]\s*\),?\s*\n/g, '')
                        .replace(/\s+path\.resolve\([^)]+\),\s*\n/g, '')
                        .replace(/\s+['"]#formick\w+['"]\s*:\s*path\.resolve\([^)]*$/gm, '');
                    // Merge into existing alias object
                    const allAliases = [
                        { name: '#formickConstants', path: constantsPath },
                        { name: '#formickUtils', path: utilsPath },
                        { name: '#formickComponents', path: componentsPath },
                        { name: '#formickTypes', path: typesPath },
                        { name: '#formickHooks', path: hooksPath },
                        { name: '#formickAssets', path: assetsPath },
                        { name: '#formickMocks', path: mocksPath },
                    ];
                    // Filter out aliases that already exist with correct path
                    const aliasesToAdd = allAliases
                        .filter(alias => {
                        // Check if this specific alias already exists with correct path
                        const hasCorrectPath = cleanedContent.includes(`'${alias.name}':`) &&
                            (cleanedContent.includes(`'${alias.path}'`) || cleanedContent.includes(`"${alias.path}"`));
                        const hasAnyPath = cleanedContent.includes(`'${alias.name}'`) || cleanedContent.includes(`"${alias.name}"`);
                        // Update if exists with wrong path, add if doesn't exist
                        if (hasCorrectPath) {
                            return false; // Already correct, skip
                        }
                        // If exists with wrong path, we'll replace it
                        if (hasAnyPath) {
                            // Remove old alias entry - match the entire line including newline
                            cleanedContent = cleanedContent.replace(new RegExp(`\\s*['"]${alias.name.replace('#', '\\#')}['"]\\s*:[^,\\n}]+(,)?\\s*\\n?`, 'g'), '');
                        }
                        return true; // Add this alias
                    })
                        .map(alias => `      '${alias.name}': path.resolve(${dirnameSyntax}, '${alias.path}'),`);
                    if (aliasesToAdd.length === 0) {
                        // Just clean up and return
                        updatedConfig = updatedConfig.replace(aliasBlockMatch[0], aliasStart + cleanedContent + closingBrace);
                    }
                    else {
                        const newAliases = aliasesToAdd.join('\n');
                        // Check if the last line ends with a comma
                        const lines = cleanedContent.split('\n').filter((line) => line.trim());
                        const lastNonEmptyLine = lines[lines.length - 1] || '';
                        const needsComma = !lastNonEmptyLine.trim().endsWith(',') && lastNonEmptyLine.trim().length > 0;
                        // Add comma to last line if needed, then add new aliases
                        if (needsComma && lines.length > 0) {
                            lines[lines.length - 1] = lines[lines.length - 1].replace(/([^,])$/, '$1,');
                            const updatedContent = lines.join('\n');
                            updatedConfig = updatedConfig.replace(aliasBlockMatch[0], aliasStart + updatedContent + '\n' + newAliases + closingBrace);
                        }
                        else {
                            updatedConfig = updatedConfig.replace(aliasBlockMatch[0], aliasStart + cleanedContent + '\n' + newAliases + closingBrace);
                        }
                    }
                }
                else {
                    // Create new resolve object with aliases
                    const aliasConfig = `
    resolve: {
      alias: {
      '#formickConstants': path.resolve(${dirnameSyntax}, '${constantsPath}'),
      '#formickUtils': path.resolve(${dirnameSyntax}, '${utilsPath}'),
      '#formickComponents': path.resolve(${dirnameSyntax}, '${componentsPath}'),
      '#formickTypes': path.resolve(${dirnameSyntax}, '${typesPath}'),
      '#formickHooks': path.resolve(${dirnameSyntax}, '${hooksPath}'),
      '#formickAssets': path.resolve(${dirnameSyntax}, '${assetsPath}'),
      '#formickMocks': path.resolve(${dirnameSyntax}, '${mocksPath}'),
      },
    },`;
                    // Insert alias configuration
                    if (viteConfig.includes('export default defineConfig({')) {
                        updatedConfig = updatedConfig.replace(/export default defineConfig\(\{/, `export default defineConfig({${aliasConfig}`);
                    }
                }
                await fs_extra_1.default.writeFile(viteConfigFile, updatedConfig);
                console.log(chalk_1.default.green('✓ Updated Vite config with path aliases'));
            }
        }
        catch (error) {
            console.warn(chalk_1.default.yellow('⚠️ Could not update Vite config automatically. Please add path aliases manually.'));
            if (error instanceof Error) {
                console.warn(chalk_1.default.yellow(`   Error: ${error.message}`));
            }
        }
    }
    // Setup tsconfig.json paths
    const tsconfigPath = path_1.default.resolve(cwd, 'tsconfig.json');
    if (await fs_extra_1.default.pathExists(tsconfigPath)) {
        try {
            let tsconfigContent = await fs_extra_1.default.readFile(tsconfigPath, 'utf-8');
            // Remove comments from JSON (TypeScript allows comments but JSON.parse doesn't)
            tsconfigContent = tsconfigContent.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*/g, '');
            const tsconfig = JSON.parse(tsconfigContent);
            if (!tsconfig.compilerOptions) {
                tsconfig.compilerOptions = {};
            }
            // Add baseUrl if not present (required for paths to work)
            if (!tsconfig.compilerOptions.baseUrl) {
                tsconfig.compilerOptions.baseUrl = '.';
            }
            if (!tsconfig.compilerOptions.paths) {
                tsconfig.compilerOptions.paths = {};
            }
            // Determine base path for formbuilder (e.g., src/formbuilder)
            const basePath = config.basePath || 'src/';
            const formbuilderBasePath = basePath.replace(/\/$/, '') + '/formbuilder';
            // Get user-specified paths - #formickComponents should point to base formbuilder directory
            const componentsPath = `./${formbuilderBasePath.replace(/\/$/, '')}`;
            const utilsPath = `./${(config.aliases.utils.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/utils`).replace(/\/$/, '')}`;
            const constantsPath = `./${(config.aliases.constants.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/constants`).replace(/\/$/, '')}`;
            const typesPath = `./${(config.aliases.types.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/types`).replace(/\/$/, '')}`;
            const hooksPath = `./${(config.aliases.hooks.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/hooks`).replace(/\/$/, '')}`;
            const assetsPath = `./${(config.aliases.assets.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/assets`).replace(/\/$/, '')}`;
            const mocksPath = `./${(config.aliases.mocks.replace(/^[@#]/, basePath).replace(/\/$/, '') || `${formbuilderBasePath}/mocks`).replace(/\/$/, '')}`;
            // Define all possible path mappings
            const allPathMappings = [
                { alias: '#formickUtils/*', path: `${utilsPath}/*` },
                { alias: '#formickUtils', path: utilsPath },
                { alias: '#formickComponents/*', path: `${componentsPath}/*` },
                { alias: '#formickComponents', path: componentsPath },
                { alias: '#formickConstants/*', path: `${constantsPath}/*` },
                { alias: '#formickConstants', path: constantsPath },
                { alias: '#formickTypes/*', path: `${typesPath}/*` },
                { alias: '#formickTypes', path: typesPath },
                { alias: '#formickHooks/*', path: `${hooksPath}/*` },
                { alias: '#formickHooks', path: hooksPath },
                { alias: '#formickAssets/*', path: `${assetsPath}/*` },
                { alias: '#formickAssets', path: assetsPath },
                { alias: '#formickMocks/*', path: `${mocksPath}/*` },
                { alias: '#formickMocks', path: mocksPath },
            ];
            // Only add if not already present
            let updated = false;
            for (const mapping of allPathMappings) {
                if (!tsconfig.compilerOptions.paths[mapping.alias]) {
                    tsconfig.compilerOptions.paths[mapping.alias] = [mapping.path];
                    updated = true;
                }
            }
            if (updated) {
                await fs_extra_1.default.writeFile(tsconfigPath, JSON.stringify(tsconfig, null, 2));
                console.log(chalk_1.default.green('✓ Updated tsconfig.json with path aliases'));
            }
        }
        catch (error) {
            console.warn(chalk_1.default.yellow('⚠️ Could not update tsconfig.json automatically. Please add path mappings manually.'));
            if (error instanceof Error) {
                console.warn(chalk_1.default.yellow(`   Error: ${error.message}`));
            }
        }
    }
    else {
        console.warn(chalk_1.default.yellow('⚠️ tsconfig.json not found. Path aliases will not be configured.'));
    }
}
async function setupCSSImports(cwd) {
    // Add Astral UI CSS imports directly to main.tsx/main.jsx
    const astralUIImports = [
        'import "@cloudwick/astral-ui/dist/css/index.min.css";',
        'import "@cloudwick/astral-ui/dist/css/fonts.min.css";'
    ];
    // Helper function to remove duplicate imports
    const removeDuplicateImports = (lines) => {
        const seenImports = new Set();
        return lines.filter(line => {
            const trimmedLine = line.trim();
            // Check if this is an astral-ui CSS import
            if (trimmedLine.startsWith('import') && trimmedLine.includes('@cloudwick/astral-ui') && trimmedLine.includes('.css')) {
                // Extract the CSS file name for comparison
                const cssFile = trimmedLine.match(/([^/]+\.css)/)?.[1];
                if (cssFile && seenImports.has(cssFile)) {
                    console.log(chalk_1.default.yellow(`🗑️ Removing duplicate import: ${trimmedLine}`));
                    return false; // Remove duplicate
                }
                if (cssFile) {
                    seenImports.add(cssFile);
                }
            }
            return true; // Keep the line
        });
    };
    const possibleMainFiles = [
        'src/main.tsx',
        'src/main.jsx',
        'src/index.tsx',
        'src/index.jsx'
    ];
    for (const mainFile of possibleMainFiles) {
        const fullPath = path_1.default.resolve(cwd, mainFile);
        if (await fs_extra_1.default.pathExists(fullPath)) {
            let mainContent = await fs_extra_1.default.readFile(fullPath, 'utf-8');
            let lines = mainContent.split('\n');
            // First, remove any existing duplicates
            const originalLength = lines.length;
            lines = removeDuplicateImports(lines);
            const duplicatesRemoved = originalLength !== lines.length;
            let updated = false;
            let insertIndex = 0;
            // Find the insertion point - after all local CSS imports but before component imports
            let lastLocalCssIndex = -1;
            // Find the last local CSS import (like './index.css', './App.css', etc.)
            for (let i = 0; i < lines.length; i++) {
                const line = lines[i].trim();
                if (line.startsWith('import ') &&
                    (line.includes("'./") || line.includes('"./'))) {
                    if (line.includes('.css')) {
                        lastLocalCssIndex = i;
                    }
                }
            }
            // If we found local CSS imports, insert after them
            if (lastLocalCssIndex !== -1) {
                insertIndex = lastLocalCssIndex + 1;
            }
            else {
                // Otherwise, find React imports and insert after them
                const reactImportIndex = lines.findIndex(line => line.includes('import React') ||
                    line.includes('import { StrictMode }') ||
                    line.includes('import { createRoot }'));
                if (reactImportIndex !== -1) {
                    insertIndex = reactImportIndex + 1;
                }
            }
            // Add each Astral UI import if it doesn't already exist
            for (const importStatement of astralUIImports) {
                // Extract the CSS file path from the import statement
                const cssPath = importStatement.match(/"([^"]+)"/)?.[1];
                if (!cssPath)
                    continue;
                // Multiple checks to ensure we don't add duplicates:
                // 1. Check if the exact import statement exists
                // 2. Check if any line contains the CSS path (handles different quote styles)
                // 3. Check for variations in spacing and formatting
                const existsAlready = lines.some(line => {
                    const trimmedLine = line.trim();
                    return (trimmedLine === importStatement.trim() ||
                        trimmedLine.includes(cssPath) ||
                        (trimmedLine.startsWith('import') && trimmedLine.includes('@cloudwick/astral-ui') && trimmedLine.includes(cssPath.split('/').pop() || '')));
                });
                if (!existsAlready) {
                    lines.splice(insertIndex, 0, importStatement);
                    insertIndex++; // Increment for next import
                    updated = true;
                    console.log(chalk_1.default.green(`✓ Added ${cssPath} import to ${mainFile}`));
                }
                else {
                    console.log(chalk_1.default.yellow(`ℹ ${cssPath} import already exists in ${mainFile}`));
                }
            }
            if (updated || duplicatesRemoved) {
                await fs_extra_1.default.writeFile(fullPath, lines.join('\n'));
                if (duplicatesRemoved) {
                    console.log(chalk_1.default.green(`✓ Cleaned up duplicate imports in ${mainFile}`));
                }
            }
            break;
        }
    }
}
async function checkTailwindInstallation(cwd) {
    try {
        // Check if package.json exists
        const packageJsonPath = path_1.default.resolve(cwd, 'package.json');
        if (!await fs_extra_1.default.pathExists(packageJsonPath)) {
            console.log(chalk_1.default.yellow('⚠️ No package.json found. Please make sure you\'re in a valid project directory.'));
            return;
        }
        const packageJson = JSON.parse(await fs_extra_1.default.readFile(packageJsonPath, 'utf-8'));
        const dependencies = { ...packageJson.dependencies, ...packageJson.devDependencies };
        const tailwindVersion = dependencies.tailwindcss;
        if (!tailwindVersion) {
            // Tailwind CSS not installed
            console.log(chalk_1.default.yellow('\n⚠️ Tailwind CSS is not installed in your project.'));
            console.log(chalk_1.default.cyan('📦 Please install Tailwind CSS v3 before proceeding:'));
            console.log(chalk_1.default.white('   npm install -D tailwindcss@^3.0.0 postcss autoprefixer'));
            console.log(chalk_1.default.white('   npx tailwindcss init -p'));
            console.log('');
            const { proceed } = await inquirer_1.default.prompt([
                {
                    type: 'confirm',
                    name: 'proceed',
                    message: 'Do you want to continue without Tailwind CSS? (Components may not work properly)',
                    default: false,
                },
            ]);
            if (!proceed) {
                console.log(chalk_1.default.red('Installation cancelled. Please install Tailwind CSS v3 and try again.'));
                process.exit(1);
            }
        }
        else {
            // Check Tailwind version
            const versionMatch = tailwindVersion.match(/(\d+)\./);
            const majorVersion = versionMatch ? parseInt(versionMatch[1]) : null;
            if (majorVersion === 4) {
                // Tailwind v4 detected
                console.log(chalk_1.default.red('\n❌ Tailwind CSS v4 detected!'));
                console.log(chalk_1.default.yellow('⚠️ This CLI requires Tailwind CSS v3 for compatibility.'));
                console.log(chalk_1.default.cyan('📦 Please downgrade to Tailwind CSS v3:'));
                console.log(chalk_1.default.white('   npm uninstall tailwindcss'));
                console.log(chalk_1.default.white('   npm install -D tailwindcss@^3.0.0'));
                console.log('');
                const { proceed } = await inquirer_1.default.prompt([
                    {
                        type: 'confirm',
                        name: 'proceed',
                        message: 'Do you want to continue with Tailwind v4? (Components may not work properly)',
                        default: false,
                    },
                ]);
                if (!proceed) {
                    console.log(chalk_1.default.red('Installation cancelled. Please downgrade to Tailwind CSS v3 and try again.'));
                    process.exit(1);
                }
            }
            else if (majorVersion === 3) {
                // Tailwind v3 detected - perfect!
                console.log(chalk_1.default.green('✓ Tailwind CSS v3 detected - perfect!'));
            }
            else if (majorVersion && majorVersion < 3) {
                // Older version detected
                console.log(chalk_1.default.yellow(`\n⚠️ Tailwind CSS v${majorVersion} detected.`));
                console.log(chalk_1.default.cyan('📦 Please upgrade to Tailwind CSS v3:'));
                console.log(chalk_1.default.white('   npm install -D tailwindcss@^3.0.0'));
                console.log('');
                const { proceed } = await inquirer_1.default.prompt([
                    {
                        type: 'confirm',
                        name: 'proceed',
                        message: 'Do you want to continue with the older version? (Components may not work properly)',
                        default: false,
                    },
                ]);
                if (!proceed) {
                    console.log(chalk_1.default.red('Installation cancelled. Please upgrade to Tailwind CSS v3 and try again.'));
                    process.exit(1);
                }
            }
        }
    }
    catch (error) {
        console.log(chalk_1.default.yellow('⚠️ Could not check Tailwind CSS installation. Proceeding anyway...'));
    }
}
// Utility function to clean up duplicate CSS imports
async function cleanupDuplicateImports(cwd = process.cwd()) {
    const possibleMainFiles = [
        'src/main.tsx',
        'src/main.jsx',
        'src/index.tsx',
        'src/index.jsx'
    ];
    for (const mainFile of possibleMainFiles) {
        const fullPath = path_1.default.resolve(cwd, mainFile);
        if (await fs_extra_1.default.pathExists(fullPath)) {
            const mainContent = await fs_extra_1.default.readFile(fullPath, 'utf-8');
            const lines = mainContent.split('\n');
            const seenImports = new Set();
            const cleanedLines = lines.filter(line => {
                const trimmedLine = line.trim();
                // Check if this is an astral-ui CSS import
                if (trimmedLine.startsWith('import') && trimmedLine.includes('@cloudwick/astral-ui') && trimmedLine.includes('.css')) {
                    // Extract the CSS file name for comparison
                    const cssFile = trimmedLine.match(/([^/]+\.css)/)?.[1];
                    if (cssFile && seenImports.has(cssFile)) {
                        console.log(chalk_1.default.yellow(`🗑️ Removing duplicate import: ${trimmedLine}`));
                        return false; // Remove duplicate
                    }
                    if (cssFile) {
                        seenImports.add(cssFile);
                    }
                }
                return true; // Keep the line
            });
            if (cleanedLines.length !== lines.length) {
                await fs_extra_1.default.writeFile(fullPath, cleanedLines.join('\n'));
                console.log(chalk_1.default.green(`✓ Cleaned up duplicate imports in ${mainFile}`));
            }
            else {
                console.log(chalk_1.default.green(`✓ No duplicate imports found in ${mainFile}`));
            }
            return;
        }
    }
    console.log(chalk_1.default.yellow('ℹ No main entry file found'));
}
async function initCommand(options = {}) {
    const cwd = path_1.default.resolve(options.cwd || process.cwd());
    // Check if already initialized
    const existingConfig = await (0, config_1.getConfig)(cwd);
    if (existingConfig && !options.yes) {
        const { proceed } = await inquirer_1.default.prompt([
            {
                type: 'confirm',
                name: 'proceed',
                message: 'Configuration already exists. Do you want to overwrite it?',
                default: false,
            },
        ]);
        if (!proceed) {
            return;
        }
    }
    let config;
    // Always ask for basePath, even with -y flag
    const basePathAnswer = await inquirer_1.default.prompt([
        {
            type: 'input',
            name: 'basePath',
            message: 'What should be the base path for the component?',
            default: 'src/',
            validate: (input) => {
                if (!input.trim())
                    return 'Base path cannot be empty';
                return true;
            },
            filter: (input) => {
                // Ensure path ends with /
                return input.trim().replace(/\/$/, '') + '/';
            }
        },
    ]);
    if (options.yes) {
        config = {
            ...(0, config_1.getDefaultConfig)(),
            basePath: basePathAnswer.basePath,
        };
    }
    else {
        // Interactive configuration
        const answers = await inquirer_1.default.prompt([
            {
                type: 'confirm',
                name: 'typescript',
                message: 'Would you like to use TypeScript?',
                default: true,
            },
            {
                type: 'confirm',
                name: 'cssVariables',
                message: 'Would you like to use CSS variables for colors?',
                default: true,
            },
            {
                type: 'input',
                name: 'tailwindConfig',
                message: 'Where is your tailwind.config.js located?',
                default: 'tailwind.config.js',
            },
            {
                type: 'input',
                name: 'tailwindCss',
                message: 'Where is your global CSS file?',
                default: 'src/app/globals.css',
            },
        ]);
        config = {
            style: 'default',
            rsc: false,
            tsx: answers.typescript,
            basePath: basePathAnswer.basePath,
            tailwind: {
                config: answers.tailwindConfig,
                css: answers.tailwindCss,
                baseColor: 'slate',
                cssVariables: answers.cssVariables,
            },
            aliases: {
                components: '#formickComponents',
                utils: '#formickUtils',
                ui: '#formickComponents',
                constants: '#formickConstants',
                types: '#formickTypes',
                hooks: '#formickHooks',
                assets: '#formickAssets',
                mocks: '#formickMocks',
            },
        };
    }
    // Check Tailwind CSS installation and version
    await checkTailwindInstallation(cwd);
    const spinner = (0, ora_1.default)('Creating configuration...').start();
    try {
        // Create base path directory if it doesn't exist
        const basePath = config.basePath || 'src/';
        const baseDir = path_1.default.resolve(cwd, basePath);
        await fs_extra_1.default.ensureDir(baseDir);
        // Also ensure lib directory exists (for utils.ts)
        const libDir = path_1.default.resolve(cwd, 'src/lib');
        await fs_extra_1.default.ensureDir(libDir);
        // Create utils file if it doesn't exist
        const libUtilsPath = path_1.default.resolve(cwd, 'src/lib/utils.ts');
        if (!await fs_extra_1.default.pathExists(libUtilsPath)) {
            const utilsContent = `import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

export function generateId(): string {
  return Math.random().toString(36).substr(2, 9);
}

export function generateIdWithPrefix(prefix: string): string {
  return \`\${prefix}_\${generateId()}\`;
}`;
            await fs_extra_1.default.writeFile(libUtilsPath, utilsContent);
        }
        // Create essential supporting files
        await createEssentialFiles(cwd, config);
        // Setup CSS imports with correct Astral UI paths
        await setupCSSImports(cwd);
        // Add combined.css import to main.tsx/main.jsx
        await addCombinedCssImport(cwd);
        // Setup Tailwind configuration
        await setupTailwindConfig(cwd);
        // Setup project aliases (Vite and TypeScript path mappings)
        await setupProjectAliases(cwd, config);
        // Write configuration
        await (0, config_1.writeConfig)(cwd, config);
        spinner.succeed('Configuration created successfully!');
        // Install required dependencies
        try {
            const { installDependencies } = await Promise.resolve().then(() => __importStar(require('../utils/dependencies')));
            const requiredDeps = [
                'clsx',
                'tailwind-merge',
                'use-immer',
                'immer', // Peer dependency for use-immer
                'zod',
                '@dnd-kit/core',
                '@dnd-kit/sortable',
                '@dnd-kit/utilities',
                'react-signature-canvas',
                'libphonenumber-js',
                '@cloudwick/astral-ui'
            ];
            await installDependencies(requiredDeps, cwd, {
                addToPackageJson: true
            });
        }
        catch (error) {
            console.error(chalk_1.default.red('Dependencies installation failed:'), error instanceof Error ? error.message : String(error));
        }
    }
    catch (error) {
        spinner.fail('Failed to initialize');
        console.error(chalk_1.default.red('Error:'), error);
        process.exit(1);
    }
}
//# sourceMappingURL=init.js.map