"use strict";
/**
 * @file
 * Setup script for Drupal Layout Builder integration
 *
 * This script helps Drupal modules integrate @bluefly/llm-ui components
 * with Layout Builder by creating the necessary bridge files.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupDrupalIntegration = setupDrupalIntegration;
const fs_1 = require("fs");
const path_1 = require("path");
/**
 * Default setup options
 */
const defaultOptions = {
    namespace: 'Drupal\\llm\\Plugin\\Block'
};
/**
 * Setup Drupal Layout Builder integration
 */
function setupDrupalIntegration(options) {
    const { modulePath, moduleId, namespace } = options;
    // Create necessary directories
    const dirs = [
        (0, path_1.join)(modulePath, 'js'),
        (0, path_1.join)(modulePath, 'css'),
        (0, path_1.join)(modulePath, 'src', 'Plugin', 'Block'),
        (0, path_1.join)(modulePath, 'templates')
    ];
    dirs.forEach(dir => {
        if (!(0, fs_1.existsSync)(dir)) {
            (0, fs_1.mkdirSync)(dir, { recursive: true });
        }
    });
    // Create React bridge file
    const reactBridgeContent = generateReactBridge(moduleId);
    (0, fs_1.writeFileSync)((0, path_1.join)(modulePath, 'js', 'react-bridge.js'), reactBridgeContent);
    // Create CSS integration file
    const cssContent = generateCSSIntegration();
    (0, fs_1.writeFileSync)((0, path_1.join)(modulePath, 'css', 'llm-ui-integration.css'), cssContent);
    // Create example block plugin
    const blockContent = generateBlockPlugin(namespace, moduleId);
    (0, fs_1.writeFileSync)((0, path_1.join)(modulePath, 'src', 'Plugin', 'Block', 'ReactDashboardBlock.php'), blockContent);
    // Create Twig template
    const templateContent = generateTwigTemplate();
    (0, fs_1.writeFileSync)((0, path_1.join)(modulePath, 'templates', 'react-dashboard-block.html.twig'), templateContent);
    console.log('✅ Drupal Layout Builder integration setup complete!');
    console.log(`📁 Files created in: ${modulePath}`);
    console.log('🔧 Next steps:');
    console.log('1. Enable Layout Builder on your content types');
    console.log('2. Add the new React blocks to your layouts');
    console.log('3. Configure components via the block settings');
}
/**
 * Generate React bridge JavaScript
 */
function generateReactBridge(moduleId) {
    return `/**
 * @file
 * React bridge for @bluefly/llm-ui components in Drupal Layout Builder
 */

import React from 'react';
import { createRoot } from 'react-dom/client';
import { 
  Dashboard, 
  Grid, 
  Card, 
  Charts,
  LayoutBuilderProvider 
} from '@bluefly/llm-ui/drupal-layout-builder';

/**
 * Initialize React components in Drupal
 */
(function (Drupal) {
  'use strict';

  /**
   * React component bridge behavior
   */
  Drupal.behaviors.${moduleId}ReactBridge = {
    attach: function (context, settings) {
      // Mount Dashboard components
      const dashboardElements = context.querySelectorAll('[data-react-component="dashboard"]');
      dashboardElements.forEach(element => {
        if (!element.hasAttribute('data-react-mounted')) {
          const config = JSON.parse(element.dataset.config || '{}');
          const root = createRoot(element);
          
          root.render(
            React.createElement(LayoutBuilderProvider, { 
              drupalSettings: settings 
            }, 
              React.createElement(Dashboard, config)
            )
          );
          
          element.setAttribute('data-react-mounted', 'true');
        }
      });
      
      // Mount Grid components
      const gridElements = context.querySelectorAll('[data-react-component="grid"]');
      gridElements.forEach(element => {
        if (!element.hasAttribute('data-react-mounted')) {
          const config = JSON.parse(element.dataset.config || '{}');
          const root = createRoot(element);
          
          root.render(
            React.createElement(LayoutBuilderProvider, { 
              drupalSettings: settings 
            }, 
              React.createElement(Grid, config)
            )
          );
          
          element.setAttribute('data-react-mounted', 'true');
        }
      });
    }
  };

})(Drupal);`;
}
/**
 * Generate CSS integration
 */
function generateCSSIntegration() {
    return `/**
 * @file
 * CSS integration for @bluefly/llm-ui components in Drupal Layout Builder
 */

/* Layout Builder integration styles */
.react-component-wrapper {
  position: relative;
  min-height: 100px;
  padding: 16px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #ffffff;
}

.react-component-wrapper[data-react-mounted="true"] {
  border-color: #10b981;
}

.react-component-wrapper::before {
  content: "Loading React component...";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #6b7280;
  font-size: 14px;
}

.react-component-wrapper[data-react-mounted="true"]::before {
  display: none;
}

/* Dark mode support */
@media (prefers-color-scheme: dark) {
  .react-component-wrapper {
    background: #1f2937;
    border-color: #374151;
    color: #f9fafb;
  }
  
  .react-component-wrapper[data-react-mounted="true"] {
    border-color: #059669;
  }
}

/* Responsive design */
@media (max-width: 768px) {
  .react-component-wrapper {
    padding: 12px;
    min-height: 80px;
  }
}`;
}
/**
 * Generate PHP block plugin
 */
function generateBlockPlugin(namespace, moduleId) {
    return `<?php

declare(strict_types=1);

namespace ${namespace};

use Drupal\\Core\\Block\\BlockBase;
use Drupal\\Core\\Form\\FormStateInterface;

/**
 * Provides a React Dashboard block using @bluefly/llm-ui.
 *
 * @Block(
 *   id = "${moduleId}_react_dashboard",
 *   admin_label = @Translation("React Dashboard (LLM UI)"),
 *   category = @Translation("AI Components")
 * )
 */
class ReactDashboardBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration(): array {
    return [
      'dashboard_type' => 'metrics',
      'grid_columns' => 3,
      'theme_variant' => 'default',
      'show_filters' => TRUE,
      'refresh_interval' => 30,
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state): array {
    $config = $this->getConfiguration();

    $form['dashboard_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Dashboard Type'),
      '#options' => [
        'metrics' => $this->t('Metrics Dashboard'),
        'analytics' => $this->t('Analytics Dashboard'),
        'monitoring' => $this->t('System Monitoring'),
        'custom' => $this->t('Custom Dashboard'),
      ],
      '#default_value' => $config['dashboard_type'],
      '#description' => $this->t('Select the type of dashboard to display.'),
    ];

    $form['grid_columns'] = [
      '#type' => 'number',
      '#title' => $this->t('Grid Columns'),
      '#min' => 1,
      '#max' => 6,
      '#default_value' => $config['grid_columns'],
      '#description' => $this->t('Number of columns in the dashboard grid.'),
    ];

    $form['theme_variant'] = [
      '#type' => 'select',
      '#title' => $this->t('Theme Variant'),
      '#options' => [
        'default' => $this->t('Default'),
        'dark' => $this->t('Dark Mode'),
        'light' => $this->t('Light Mode'),
        'high-contrast' => $this->t('High Contrast'),
      ],
      '#default_value' => $config['theme_variant'],
    ];

    $form['show_filters'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Show Filters'),
      '#default_value' => $config['show_filters'],
      '#description' => $this->t('Display filter controls in the dashboard.'),
    ];

    $form['refresh_interval'] = [
      '#type' => 'number',
      '#title' => $this->t('Refresh Interval (seconds)'),
      '#min' => 5,
      '#max' => 300,
      '#default_value' => $config['refresh_interval'],
      '#description' => $this->t('How often to refresh dashboard data (in seconds).'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state): void {
    $this->configuration['dashboard_type'] = $form_state->getValue('dashboard_type');
    $this->configuration['grid_columns'] = (int) $form_state->getValue('grid_columns');
    $this->configuration['theme_variant'] = $form_state->getValue('theme_variant');
    $this->configuration['show_filters'] = (bool) $form_state->getValue('show_filters');
    $this->configuration['refresh_interval'] = (int) $form_state->getValue('refresh_interval');
  }

  /**
   * {@inheritdoc}
   */
  public function build(): array {
    $config = $this->getConfiguration();

    // Prepare React component configuration
    $reactConfig = [
      'type' => $config['dashboard_type'],
      'columns' => $config['grid_columns'],
      'theme' => $config['theme_variant'],
      'showFilters' => $config['show_filters'],
      'refreshInterval' => $config['refresh_interval'] * 1000, // Convert to milliseconds
      'apiEndpoint' => '/api/llm/dashboard-data',
      'accessToken' => '{{ csrf_token }}', // Will be replaced by Twig
    ];

    return [
      '#theme' => 'react_dashboard_block',
      '#component' => 'dashboard',
      '#config' => $reactConfig,
      '#attached' => [
        'library' => [
          '${moduleId}/react-integration',
        ],
        'drupalSettings' => [
          'llmUi' => [
            'dashboards' => [
              $this->getPluginId() => $reactConfig,
            ],
          ],
        ],
      ],
    ];
  }

}`;
}
/**
 * Generate Twig template
 */
function generateTwigTemplate() {
    return `{#
/**
 * @file
 * Template for React Dashboard block using @bluefly/llm-ui
 *
 * Available variables:
 * - component: The React component name
 * - config: Component configuration object
 * - attributes: HTML attributes for the wrapper
 */
#}

<div{{ attributes.addClass('react-component-wrapper') }} 
     data-react-component="{{ component }}"
     data-config="{{ config|json_encode|e('html_attr') }}">
  {# Fallback content for users without JavaScript #}
  <noscript>
    <div class="messages messages--warning">
      {{ 'This dashboard requires JavaScript to function properly.'|t }}
    </div>
  </noscript>
</div>`;
}
/**
 * Command line interface
 */
if (import.meta.url === `file://${process.argv[1]}`) {
    const modulePath = process.argv[2];
    const moduleId = process.argv[3] || 'llm';
    const namespace = process.argv[4] || 'Drupal\\llm\\Plugin\\Block';
    if (!modulePath) {
        console.error('Usage: node setup.js <module-path> [module-id] [namespace]');
        process.exit(1);
    }
    setupDrupalIntegration({
        modulePath,
        moduleId,
        namespace
    });
}
//# sourceMappingURL=setup.js.map