/**
 * Mockup Generator
 *
 * Generates high-quality ASCII wireframes for UI components.
 * Used in FASE 1.5: UI/UX Design (conception phase).
 *
 * MORPH-SPEC 3.0
 */

/**
 * Generate wireframe based on component spec
 * @param {Object} componentSpec - Component specification
 * @returns {string} ASCII wireframe
 */
export function generateWireframe(componentSpec) {
  switch (componentSpec.type) {
    case 'form':
      return generateFormWireframe(componentSpec);
    case 'list':
    case 'data-grid':
      return generateListWireframe(componentSpec);
    case 'dashboard':
      return generateDashboardWireframe(componentSpec);
    case 'wizard':
      return generateWizardWireframe(componentSpec);
    case 'file-upload':
      return generateFileUploadWireframe(componentSpec);
    case 'confirm-dialog':
      return generateConfirmDialogWireframe(componentSpec);
    case 'detail-view':
      return generateDetailViewWireframe(componentSpec);
    default:
      return generateGenericWireframe(componentSpec);
  }
}

/**
 * Generate form wireframe
 */
function generateFormWireframe(spec) {
  const { entity, operation = 'create', fields = [] } = spec;
  const title = operation === 'create' ? `Create ${entity}` : `Edit ${entity}`;

  const maxLabelLength = Math.max(...fields.map(f => (f.label || f.name).length), 15);
  const fieldWidth = 40;
  const totalWidth = maxLabelLength + fieldWidth + 10;

  const fieldLines = fields.map(field => {
    const label = (field.label || field.name).padEnd(maxLabelLength);
    const inputType = getInputType(field.type);
    const required = field.isRequired ? '*' : ' ';

    return `│  ${required} ${label}  ${inputType.padEnd(fieldWidth)} │`;
  }).join('\n');

  return `
┌${'─'.repeat(totalWidth)}┐
│  ${title.padEnd(totalWidth - 4)} │
├${'─'.repeat(totalWidth)}┤
│${' '.repeat(totalWidth)}│
${fieldLines}
│${' '.repeat(totalWidth)}│
│  ┌──────────┐  ┌────────┐${' '.repeat(totalWidth - 34)}│
│  │  ${operation === 'create' ? 'Create' : 'Save'}  │  │ Cancel │${' '.repeat(totalWidth - 34)}│
│  └──────────┘  └────────┘${' '.repeat(totalWidth - 34)}│
└${'─'.repeat(totalWidth)}┘

Legend: * = Required field
`.trim();
}

/**
 * Get input type representation
 */
function getInputType(type) {
  if (!type) return '[_________________]';

  const lower = type.toLowerCase();

  if (lower.includes('string') || lower.includes('text')) {
    return '[_________________]';
  } else if (lower.includes('int') || lower.includes('decimal') || lower.includes('number')) {
    return '[______] (number)';
  } else if (lower.includes('date') || lower.includes('datetime')) {
    return '[____/____/____] 📅';
  } else if (lower.includes('bool')) {
    return '☐ Yes  ☐ No';
  } else if (lower.includes('enum') || lower.includes('status') || lower.includes('type')) {
    return '[Select option ▼]';
  } else if (lower.includes('email')) {
    return '[___@___.___]';
  } else if (lower.includes('url')) {
    return '[https://____]';
  } else {
    return '[_________________]';
  }
}

/**
 * Generate list/grid wireframe
 */
function generateListWireframe(spec) {
  const { entity, fields = [], features = {} } = spec;
  const title = `${entity} List`;

  const headers = fields.slice(0, 5).map(f => (f.label || f.name).substring(0, 15).padEnd(15));
  const headerLine = headers.join(' │ ');

  const sampleRow = fields.slice(0, 5).map(f => {
    const sample = getSampleValue(f.type);
    return sample.substring(0, 15).padEnd(15);
  }).join(' │ ');

  const totalWidth = headers.length * 16 + headers.length - 1 + 12; // +12 for actions

  return `
┌${'─'.repeat(totalWidth + 4)}┐
│  ${title.padEnd(totalWidth - 20)}     [+ New] [⚙ Filters]   │
├${'─'.repeat(totalWidth + 4)}┤
│  ${headerLine}  │ Actions │
├${'─'.repeat(totalWidth + 4)}┤
│  ${sampleRow}  │ ✏️ 🗑️   │
│  ${sampleRow}  │ ✏️ 🗑️   │
│  ${sampleRow}  │ ✏️ 🗑️   │
${features.pagination !== false ? `├${'─'.repeat(totalWidth + 4)}┤
│  ◀ 1 2 3 ... 10 ▶${' '.repeat(totalWidth - 40)}Showing 1-10 of 47 │` : ''}
└${'─'.repeat(totalWidth + 4)}┘

${features.filtering !== false ? '\nFeatures: Search, Filter, Sort' : ''}
${features.selection !== false ? 'Selection: Multi-select with checkboxes' : ''}
`.trim();
}

/**
 * Get sample value for field type
 */
function getSampleValue(type) {
  if (!type) return 'Sample Value';

  const lower = type.toLowerCase();

  if (lower.includes('name')) return 'John Doe';
  if (lower.includes('email')) return 'user@example.com';
  if (lower.includes('phone')) return '(555) 123-4567';
  if (lower.includes('date')) return '2025-01-17';
  if (lower.includes('status')) return 'Active';
  if (lower.includes('amount') || lower.includes('price')) return '$99.99';
  if (lower.includes('quantity') || lower.includes('count')) return '42';
  if (lower.includes('bool')) return 'Yes';

  return 'Sample';
}

/**
 * Generate dashboard wireframe
 */
function generateDashboardWireframe(spec) {
  const { widgets = [] } = spec;

  const hasStats = widgets.some(w => w.type === 'stat-card');
  const hasChart = widgets.some(w => w.type === 'chart');
  const hasTable = widgets.some(w => w.type === 'data-table');

  return `
┌────────────────────────────────────────────────────────────────────────────┐
│  Dashboard Overview                                    [User Icon] ▼       │
├────────────────────────────────────────────────────────────────────────────┤
│                                                                            │
${hasStats ? `│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐              │
│  │  Total Sales │  │ New Orders   │  │ Revenue      │              │
│  │  $125,430    │  │  47          │  │  +12.5%      │              │
│  │  +8.2% ↑     │  │  +5 today    │  │  This month  │              │
│  └──────────────┘  └──────────────┘  └──────────────┘              │
│                                                                            │` : ''}
${hasChart ? `│  ┌────────────────────────────────────────────────────────────────┐  │
│  │  Sales Trend (Last 30 Days)                                   │  │
│  │                                                                │  │
│  │  $   ╭─╮                                                       │  │
│  │      │ │     ╭─╮                                               │  │
│  │      │ │   ╭─╯ ╰─╮   ╭─╮                                       │  │
│  │  ────┴─┴───┴─────┴───┴─┴─────────────────────────────────────  │  │
│  │      Week 1   Week 2   Week 3   Week 4                        │  │
│  └────────────────────────────────────────────────────────────────┘  │
│                                                                            │` : ''}
${hasTable ? `│  ┌────────────────────────────────────────────────────────────────┐  │
│  │  Recent Orders                                    [View All →] │  │
│  ├────────────────────────────────────────────────────────────────┤  │
│  │  Order #    Customer        Amount    Status      Actions      │  │
│  ├────────────────────────────────────────────────────────────────┤  │
│  │  #1234      John Doe        $99.99    Pending     👁️ ✏️        │  │
│  │  #1233      Jane Smith      $149.99   Completed   👁️ ✏️        │  │
│  │  #1232      Bob Johnson     $79.99    Shipped     👁️ ✏️        │  │
│  └────────────────────────────────────────────────────────────────┘  │` : ''}
│                                                                            │
└────────────────────────────────────────────────────────────────────────────┘
`.trim();
}

/**
 * Generate wizard wireframe
 */
function generateWizardWireframe(spec) {
  const { steps = [] } = spec;
  const currentStep = steps[0] || { number: 1, title: 'Step 1' };

  const stepIndicators = steps.map((step, i) => {
    const isCurrent = i === 0;
    return isCurrent ? `● ${step.number}` : `○ ${step.number}`;
  }).join('  ──  ');

  return `
┌────────────────────────────────────────────────────────────────────────────┐
│  ${currentStep.title.padEnd(70)} │
├────────────────────────────────────────────────────────────────────────────┤
│                                                                            │
│  Progress: ${stepIndicators.padEnd(60)} │
│                                                                            │
│  ┌──────────────────────────────────────────────────────────────────────┐ │
│  │                                                                      │ │
│  │  {Step ${currentStep.number} Content}                                        │ │
│  │  - Input fields                                                      │ │
│  │  - Instructions                                                      │ │
│  │  - Validation messages                                               │ │
│  │                                                                      │ │
│  └──────────────────────────────────────────────────────────────────────┘ │
│                                                                            │
│  ┌────────┐                                               ┌────────────┐  │
│  │  Back  │                                               │  Next  →   │  │
│  └────────┘                                               └────────────┘  │
└────────────────────────────────────────────────────────────────────────────┘
`.trim();
}

/**
 * Generate file upload wireframe
 */
function generateFileUploadWireframe(spec) {
  const { maxSize = '10MB', allowedTypes = ['.jpg', '.png'] } = spec;

  return `
┌────────────────────────────────────────────────────────────────────────────┐
│  Upload File                                                               │
├────────────────────────────────────────────────────────────────────────────┤
│                                                                            │
│  ┌──────────────────────────────────────────────────────────────────────┐ │
│  │                                                                      │ │
│  │                          📷 Drag & Drop                              │ │
│  │                                                                      │ │
│  │                  Drag your file here or click to browse              │ │
│  │                                                                      │ │
│  │                   Accepted: ${allowedTypes.join(', ').padEnd(30)} │ │
│  │                   Max size: ${maxSize.padEnd(30)}                    │ │
│  │                                                                      │ │
│  └──────────────────────────────────────────────────────────────────────┘ │
│                                                                            │
│  [Preview will appear here after file selection]                          │
│                                                                            │
│  ┌────────────┐  ┌────────┐                                               │
│  │  Upload    │  │ Cancel │                                               │
│  └────────────┘  └────────┘                                               │
└────────────────────────────────────────────────────────────────────────────┘
`.trim();
}

/**
 * Generate confirm dialog wireframe
 */
function generateConfirmDialogWireframe(spec) {
  const { entity, operation = 'delete' } = spec;

  return `
            ┌────────────────────────────────────────┐
            │  Confirm ${operation}                  │
            ├────────────────────────────────────────┤
            │                                        │
            │  Are you sure you want to ${operation}  │
            │  this ${entity}?                        │
            │                                        │
            │  This action cannot be undone.         │
            │                                        │
            │  ┌────────────┐  ┌────────┐            │
            │  │  ${operation}  │  │ Cancel │            │
            │  └────────────┘  └────────┘            │
            └────────────────────────────────────────┘
`.trim();
}

/**
 * Generate detail view wireframe
 */
function generateDetailViewWireframe(spec) {
  const { entity, fields = [] } = spec;

  const fieldLines = fields.slice(0, 8).map(field => {
    const label = (field.label || field.name).padEnd(20);
    const value = getSampleValue(field.type).padEnd(30);
    return `│  ${label}: ${value}              │`;
  }).join('\n');

  return `
┌────────────────────────────────────────────────────────────────────────────┐
│  ${entity} Details                                        [✏️ Edit] [🗑️ Delete]│
├────────────────────────────────────────────────────────────────────────────┤
│                                                                            │
${fieldLines}
│                                                                            │
│  ┌────────┐                                                                │
│  │  Back  │                                                                │
│  └────────┘                                                                │
└────────────────────────────────────────────────────────────────────────────┘
`.trim();
}

/**
 * Generate generic wireframe
 */
function generateGenericWireframe(spec) {
  const { entity = 'Component', type = 'generic' } = spec;

  return `
┌────────────────────────────────────────────────────────────────────────────┐
│  ${entity} (${type})                                                        │
├────────────────────────────────────────────────────────────────────────────┤
│                                                                            │
│  [Component content will be defined based on requirements]                │
│                                                                            │
│  - Feature 1                                                               │
│  - Feature 2                                                               │
│  - Feature 3                                                               │
│                                                                            │
└────────────────────────────────────────────────────────────────────────────┘
`.trim();
}

/**
 * Generate complete UI mockup set
 */
export function generateCompleteMockupSet(uiNeeds) {
  const mockups = {};

  for (const need of uiNeeds) {
    const key = `${need.type}-${need.entity || need.operation || 'generic'}`;
    mockups[key] = generateWireframe(need);
  }

  return mockups;
}

/**
 * Format mockups for markdown output
 */
export function formatMockupsForMarkdown(mockups) {
  const sections = [];

  for (const [key, wireframe] of Object.entries(mockups)) {
    const [type, entity] = key.split('-');
    sections.push(`### ${entity} - ${type.toUpperCase()}`);
    sections.push('');
    sections.push('```');
    sections.push(wireframe);
    sections.push('```');
    sections.push('');
  }

  return sections.join('\n');
}
