name: "Figma to Laravel Component Extraction"
description: "Extract Figma component directly to Laravel Twig + LESS (unified workflow)"
version: "2.0.0"

# Workflow Execution Configuration
execution:
  mode: "strict"
  step_tracking: "mandatory"
  abort_on_skip: true
  completion_verification: true

metadata:
  category: "extract"
  complexity: "medium"
  estimated_time: "8-12 minutes"
  prerequisites:
    - "Design system must be rebranded"
    - "Figma URL with specific node selection"
    - "Figma MCP server access"
    - "Playwright MCP server access"

variables:
  figma_url: "{figma_url}"
  node_id: "{node_id}"
  component_name: "{component_name}"
  template_directory: "{template_directory}"
  css_directory: "{css_directory}"

# Mandatory Steps Checklist
mandatory_steps:
  - "design-system-check"
  - "parse-figma-url"
  - "initialize-structure"
  - "classify-component-type"
  - "resolve-output-paths"
  - "capture-reference-screenshots"
  - "create-twig-template"
  - "validate-twig-template"
  - "create-less-stylesheet"
  - "validate-less-syntax"
  - "update-build-system"
  - "add-to-example-page"
  - "build-and-test"
  - "playwright-validation"
  - "quality-validation"

steps:
  # Step 1: Design System Verification
  - id: "design-system-check"
    name: "Verify Design System Status"
    type: "validation"
    required: true
    validation:
      checks:
        - file: "sites/default/css/variables.less"
          contains: "// DESIGN SYSTEM STATUS: figma-rebranded"
          error_message: "Design system not rebranded"
        - file: "sites/default/css/base/font.less"
          contains: ["@primary_font", "@body_font", "@secondary_font"]
          error_message: "Required font variables not found in font.less"
        - file: "sites/default/css/base/font.less"
          contains: "// DESIGN SYSTEM STATUS: figma-rebranded"
          error_message: "Font system not rebranded"
      on_failure:
        action: "stop"
        message: "❌ Design system must be rebranded first. Use /mtc-rebrand <figma-url>"

  # Step 2: Parse Figma URL and Extract Semantic Component Name
  - id: "parse-figma-url"
    name: "Parse Figma URL and Extract Semantic Component Name"
    type: "workflow"
    depends_on: ["design-system-check"]
    workflow:
      actions:
        - "Extract node ID from Figma URL (e.g., node-id=26-215 → 26:215)"
        - "Validate node ID format"
        - "Use mcp__figma-desktop__get_metadata to fetch component name from Figma"
        - "Sanitize component name for filesystem (lowercase, replace spaces with hyphens, remove special chars)"
        - "If component name is empty/unavailable, fallback to node ID format"
        - "Set {component_name} variable to sanitized name (e.g., 'three-step-approach' instead of 'component-137-156352')"
      implementation_notes: |
        Use Figma metadata API to extract the actual component/layer name:
        1. Call mcp__figma-dev-mode__get_metadata with the node ID
        2. Parse the XML response to find the component name attribute
        3. Sanitize: lowercase, spaces→hyphens, remove non-alphanumeric except hyphens
        4. Example: "3 Step Approach Section" → "three-step-approach-section"
        5. Fallback: If name is missing/invalid, use "component-{node-id}"

  # Step 3: Initialize Project Structure
  - id: "initialize-structure"
    name: "Initialize Project Structure"
    type: "command"
    depends_on: ["parse-figma-url"]
    command:
      commands:
        - "mkdir -p .frontend/assets/"
        - "mkdir -p .frontend/components/"
        - "mkdir -p .frontend/figma-selections/"
      working_directory: "."

  # Step 4: Classify Component Type
  - id: "classify-component-type"
    name: "Classify Component Type and Determine Output Locations"
    type: "analysis"
    required: true
    depends_on: ["initialize-structure"]
    workflow:
      actions:
        - "Analyze Figma component semantic structure (sections, grids, cards, forms)"
        - "Determine component category based on structure"
        - "Set output paths based on category"
      classification_logic:
        page_section:
          indicators: ["full-width section", "multiple cards", "banner pattern", "hero pattern", "contains heading + content blocks"]
          template_dir: "page_blocks"
          css_dir: "blocks"
        reusable_element:
          indicators: ["single purpose", "intro pattern", "form pattern", "card grid", "carousel", "tabs"]
          template_dir: "elements"
          css_dir: "elements"
        small_partial:
          indicators: ["small UI piece", "single card", "icon group", "button group", "badge"]
          template_dir: "partials"
          css_dir: "elements"

  # Step 5: Resolve Output Paths
  - id: "resolve-output-paths"
    name: "Resolve All Output File Paths"
    type: "workflow"
    required: true
    depends_on: ["classify-component-type"]
    workflow:
      actions:
        - "Set template_directory from classification result"
        - "Set css_directory from classification result"
        - "Construct full paths for validation"
      output_variables:
        - twig_template_path: "sites/default/templates/includes/{template_directory}/{component_name}.twig"
        - less_stylesheet_path: "sites/default/css/{css_directory}/{component_name}.less"
        - documentation_path: ".frontend/components/{component_name}.md"
        - reference_screenshot_path: ".frontend/figma-selections/{component_name}-figma.png"

  # Step 6: Capture Reference Screenshots
  - id: "capture-reference-screenshots"
    name: "Capture Figma Reference Screenshots"
    type: "workflow"
    depends_on: ["resolve-output-paths"]
    workflow:
      actions:
        - "Use Figma MCP to capture component at multiple breakpoints"
        - "Save reference screenshot to .frontend/figma-selections/{component_name}-figma.png"
        - "Capture at: 375px, 768px, 1024px, 1440px"
      output_pattern: ".frontend/figma-selections/{component_name}-figma.png"

  # Step 7: Create Twig Template
  - id: "create-twig-template"
    name: "Create Twig Template from Figma Design"
    type: "conversion"
    depends_on: ["capture-reference-screenshots"]
    conversion:
      output_pattern: "{twig_template_path}"
      conversion_type: "figma_to_twig"

      operations:
        - "Extract design from Figma using mcp__figma-dev-mode tools"
        - "Create semantic HTML structure with section wrapper"
        - "Convert to Twig template with proper variable structure"
        - "Add dummy data block for preview mode (show_dummy_data)"
        - "Convert image references to direct paths: /sites/default/images/{{ variable }}"
        - "Add Twig block structure for flexible content"
        - "Add component documentation comments"
        - "CRITICAL: Use <div> wrappers for |raw content, NEVER <p> tags"

      template_structure: |
        {# Component: {component_name} #}
        {# Generated by /mtc-extract on {date} #}

        {% if show_dummy_data is defined and show_dummy_data == true %}
            {% set p = {
                'pagedata': {
                    '{Component Name}': [{
                        'Title': {'value': 'Example Title'},
                        'Content': {'value': '<p>Example content goes here.</p>'}
                    }]
                }
            } %}
        {% endif %}

        {# Variable initialization #}
        {% if title is empty %}
            {% set title = p.pagedata['{Component Name}'][0]['Title']['value'] %}
        {% endif %}

        <section class="{componentClassName}">
            <div class="wrapper">
                {# Component content #}
            </div>
        </section>

      critical_rules:
        - "NO asset() function - use /sites/default/{{ variable }}"
        - "Use .button class for buttons (no custom button CSS)"
        - "Use existing design system classes"
        - "NO <p> tags wrapping |raw content"

  # Step 8: Validate Twig Template
  - id: "validate-twig-template"
    name: "Validate Twig Template Syntax and Structure"
    type: "validation"
    required: true
    depends_on: ["create-twig-template"]
    validation:
      checks:
        - file: "{twig_template_path}"
          exists: true
          error_message: "Twig template file was not created"
        - file: "{twig_template_path}"
          not_contains: ["asset("]
          error_message: "❌ CRITICAL: Twig template uses asset() function which doesn't exist. Use direct paths: /sites/default/{{ variable }}"
          severity: "error"
        - pattern: "<p[^>]*>.*\\|raw.*</p>"
          file: "{twig_template_path}"
          error_message: "❌ CRITICAL: Detected <p> tag wrapping |raw content. Use <div> wrapper to avoid nested <p> tags from TinyMCE."
          severity: "error"
      on_failure:
        action: "stop"
        message: |
          ❌ Twig template validation failed.

          Common issues:
          - asset() function does not exist - use /sites/default/{{ variable }}
          - <p> wrapper around |raw content - use <div> to avoid nested <p> tags

  # Step 9: Create LESS Stylesheet
  - id: "create-less-stylesheet"
    name: "Create LESS Component Stylesheet"
    type: "conversion"
    depends_on: ["create-twig-template"]
    conversion:
      output_pattern: "{less_stylesheet_path}"
      conversion_type: "figma_to_less"

      operations:
        - "Extract styles from Figma design"
        - "Map colors to existing design system variables (variables.less)"
        - "Use .headingStyle() mixin for headings"
        - "Use existing .button class instead of custom button CSS"
        - "Convert responsive breakpoints to LESS media queries"
        - "Ensure BEM naming consistency"
        - "Remove redundant CSS that exists in design system"

      design_system_mapping:
        colors:
          - "Map to @primary_color, @secondary_color, @text_color, etc."
          - "Check variables.less for available color variables"
        typography:
          - "Use .headingStyle(h1) through .headingStyle(h6) mixin"
          - "Use @base_font_size, @heading_font_weight"
        spacing:
          - "Use @gutter_width, @gutter_width_mobile"
          - "Use @wrapper_width for container widths"
        buttons:
          - "Use existing .button class"
          - "Add modifiers via additional classes, not custom CSS"

  # Step 10: Validate LESS Syntax
  - id: "validate-less-syntax"
    name: "Validate LESS Syntax Before Build"
    type: "validation"
    depends_on: ["create-less-stylesheet"]
    validation:
      pre_build_checks:
        - pattern: "\\.extend\\("
          severity: "error"
          message: "Use &:extend(.class all) instead of .extend(.class)"
          auto_fix: true

        - pattern: "calc\\([^~]"
          severity: "warning"
          message: "calc() should use escaped strings: ~\"calc(...)\""
          auto_fix: true

      command: "npx lessc {less_stylesheet_path} --lint"
      on_error:
        action: "stop"
        message: "❌ LESS syntax errors detected. Review and fix before proceeding."

  # Step 11: Update Build System
  - id: "update-build-system"
    name: "Add LESS Import to Build System"
    type: "workflow"
    depends_on: ["validate-less-syntax"]
    workflow:
      actions:
        - "Add LESS import to sites/default/includes.less"
        - "Add in appropriate section (Blocks or Elements)"
        - "Validate import path is correct"
      import_format: "@import '../../sites/default/css/{css_directory}/{component_name}.less';"
      insertion_rules:
        - section: "Blocks"
          condition: "css_directory == 'blocks'"
          after_marker: "//Blocks"
        - section: "Elements"
          condition: "css_directory == 'elements'"
          after_marker: "//Elements"

  # Step 12: Add to Example Page
  - id: "add-to-example-page"
    name: "Add Component to Example Blocks Page"
    type: "workflow"
    required: true
    depends_on: ["update-build-system"]
    workflow:
      actions:
        - "Generate include statement with spacer and section header"
        - "Insert before the AUTO-GENERATED marker in example_blocks.twig"
        - "Add controller dummy data if needed"
      template: |
        {# === {COMPONENT_NAME} === #}
        <div class="spacers" style="background: blue;"></div>

        <section class="wrapper">
            <h3>{Component Display Name}</h3>
            <p>Extracted from Figma on {date}</p>
        </section>

        {% include 'includes/{template_directory}/{component_name}.twig' with {
            show_dummy_data: true
        }%}

      controller_update:
        file: "sites/default/templates/controllers/controller.example_blocks.twig.php"
        add_section: |
          /*
           * {Component Name} - Auto-generated dummy data
           * Added by /mtc-extract on {date}
           */
          // Add component-specific test data here if needed

      completion_verification:
        file: "sites/default/templates/pages/example_blocks.twig"
        contains: "includes/{template_directory}/{component_name}.twig"
        error_message: "Component not added to example_blocks.twig"

  # Step 13: Build and Test
  - id: "build-and-test"
    name: "Build and Test Integration"
    type: "command"
    depends_on: ["add-to-example-page"]
    command:
      commands:
        - "npm run dev"
      working_directory: "."
      timeout: 120

  # Step 14: Playwright Visual Validation
  - id: "playwright-validation"
    name: "Validate Component with Playwright"
    type: "workflow"
    depends_on: ["build-and-test"]
    workflow:
      actions:
        - "Navigate to localhost/example-blocks"
        - "Scroll to component section (#{component_name})"
        - "Capture screenshot at multiple breakpoints"
        - "Compare with Figma reference screenshot"
        - "Check for console errors"
      validation_url: "http://localhost/example-blocks"
      breakpoints:
        - width: 375
          name: "mobile"
        - width: 768
          name: "tablet"
        - width: 1024
          name: "desktop"
        - width: 1440
          name: "wide"
      quality_checks:
        - visual_accuracy: ">= 98%"
        - console_errors: "0"
        - responsive_behavior: "all_breakpoints_passing"

  # Step 15: Quality Validation Gate
  - id: "quality-validation"
    name: "Final Quality Validation"
    type: "validation"
    depends_on: ["playwright-validation"]
    validation:
      checks:
        - file: "{twig_template_path}"
          exists: true
          error_message: "Twig template not created"
        - file: "{less_stylesheet_path}"
          exists: true
          error_message: "LESS stylesheet not created"
        - file: "{reference_screenshot_path}"
          exists: true
          error_message: "Reference screenshot not captured"
      quality_gates:
        - visual_accuracy: ">= 98%"
        - console_errors: "0"
        - responsive_breakpoints: "all_passing"
        - design_system_compliance: ">= 85%"
        - accessibility_score: ">= AA"
      on_failure:
        action: "stop"
        message: "❌ Quality validation failed. Component does not meet production standards."

workflow_completion:
  all_steps_must_complete: true
  verify_mandatory_steps: true

  success_message: |
    🎉 **Figma Component Extraction Complete!**

    ✅ **Created Files:**
    - `{twig_template_path}`
    - `{less_stylesheet_path}`
    - `{reference_screenshot_path}`

    ✅ **Integration Status:**
    - Design System Compliance: ✓
    - Build System Updated: ✓
    - Example Page Updated: ✓
    - Playwright Validation: ✓

    📊 **Quality Metrics:**
    - Visual Accuracy: 98%+
    - Console Errors: 0
    - Responsive: All breakpoints passing
    - Accessibility: WCAG AA compliant

    🚀 **Component Usage:**
    ```twig
    {% include 'includes/{template_directory}/{component_name}.twig' with {
        'title': 'Your Title',
        'content': 'Your content here'
    } %}
    ```

    📄 **Preview at**: http://localhost/example-blocks

  failure_message: |
    ❌ **Component Extraction Failed**

    Please check the error messages above and address any issues.
    Common issues:
    - Design system not rebranded
    - Invalid Figma URL or node selection
    - Network connectivity to Figma
    - Missing MCP server access
    - Build system errors

    You can restart with `/mtc-extract <figma-url>` after fixing the problems.

validation_rules:
  - design_system_rebranded: true
  - twig_template_exists: true
  - less_stylesheet_exists: true
  - build_passed: true
  - quality_gates_passed: true
