/**
 * Frontend Artifact Builder Skill
 *
 * Suite of tools for creating elaborate, multi-component HTML artifacts
 * using modern frontend web technologies (React, Tailwind CSS, shadcn/ui).
 *
 * Use for complex artifacts requiring state management, routing, or shadcn/ui
 * components - not for simple single-file HTML/JSX artifacts.
 *
 * Stack: React 18 + TypeScript + Vite + Parcel (bundling) + Tailwind CSS + shadcn/ui
 *
 * Token Savings: 15,000+ (vs manual setup and bundling)
 */

import { execSync } from "child_process";
import * as fs from "fs";
import * as path from "path";

// =============================================================================
// DESIGN GUIDELINES (CRITICAL - Avoid "AI Slop")
// =============================================================================
/**
 * To avoid generic AI aesthetic ("AI slop"), follow these rules:
 *
 * ❌ AVOID:
 * - Excessive centered layouts
 * - Purple gradients on white backgrounds
 * - Uniform rounded corners everywhere
 * - Inter font (overused)
 * - Clichéd color schemes
 * - Predictable layouts and component patterns
 *
 * ✅ DO:
 * - Choose distinctive, beautiful fonts (not Inter, Roboto, Arial)
 * - Commit to cohesive aesthetics with sharp accent colors
 * - Use CSS variables for consistency
 * - Add meaningful animations and micro-interactions
 * - Create atmosphere with gradients, patterns, backgrounds
 * - Make unexpected, creative choices
 * - Vary between light/dark themes
 */

// =============================================================================
// TYPES
// =============================================================================

interface ArtifactConfig {
  projectName: string;
  description?: string;
  components?: string[]; // shadcn/ui components to use
  theme?: "light" | "dark" | "system";
  customFonts?: string[];
}

interface BuildResult {
  success: boolean;
  bundlePath?: string;
  bundleSize?: number;
  errors?: string[];
}

// =============================================================================
// CORE FUNCTIONS
// =============================================================================

/**
 * Step 1: Initialize a new React artifact project
 * Creates a fully configured project with React + TypeScript + Tailwind + shadcn/ui
 */
export async function initArtifact(
  config: ArtifactConfig,
): Promise<{ success: boolean; projectPath: string; message: string }> {
  const { projectName, description } = config;
  const projectPath = path.join(process.cwd(), projectName);

  try {
    // Run init script
    execSync(`bash scripts/init-artifact.sh ${projectName}`, {
      cwd: path.join(__dirname, "../../../../"),
      stdio: "pipe",
    });

    return {
      success: true,
      projectPath,
      message: `Project initialized at ${projectPath}. Includes:
        ✅ React + TypeScript (via Vite)
        ✅ Tailwind CSS 3.4.1 with shadcn/ui theming
        ✅ Path aliases (@/) configured
        ✅ 40+ shadcn/ui components pre-installed
        ✅ All Radix UI dependencies included
        ✅ Parcel configured for bundling`,
    };
  } catch (error) {
    return {
      success: false,
      projectPath,
      message: `Failed to initialize: ${error}`,
    };
  }
}

/**
 * Step 2: Get component reference for development
 * Returns information about available shadcn/ui components
 */
export function getComponentReference(): Record<
  string,
  { description: string; import: string }
> {
  return {
    // Layout
    Card: {
      description: "Container with header, content, footer",
      import: "@/components/ui/card",
    },
    Dialog: { description: "Modal dialog", import: "@/components/ui/dialog" },
    Sheet: { description: "Slide-out panel", import: "@/components/ui/sheet" },
    Tabs: { description: "Tabbed interface", import: "@/components/ui/tabs" },
    Accordion: {
      description: "Collapsible sections",
      import: "@/components/ui/accordion",
    },

    // Forms
    Button: { description: "Click actions", import: "@/components/ui/button" },
    Input: { description: "Text input", import: "@/components/ui/input" },
    Select: {
      description: "Dropdown select",
      import: "@/components/ui/select",
    },
    Checkbox: {
      description: "Toggle checkbox",
      import: "@/components/ui/checkbox",
    },
    Switch: { description: "Toggle switch", import: "@/components/ui/switch" },
    Slider: { description: "Range slider", import: "@/components/ui/slider" },
    Form: {
      description: "Form with validation",
      import: "@/components/ui/form",
    },

    // Data Display
    Table: { description: "Data table", import: "@/components/ui/table" },
    Badge: { description: "Status badge", import: "@/components/ui/badge" },
    Avatar: { description: "User avatar", import: "@/components/ui/avatar" },
    Progress: {
      description: "Progress bar",
      import: "@/components/ui/progress",
    },

    // Feedback
    Alert: { description: "Alert messages", import: "@/components/ui/alert" },
    Toast: {
      description: "Toast notifications",
      import: "@/components/ui/toast",
    },
    Tooltip: {
      description: "Hover tooltips",
      import: "@/components/ui/tooltip",
    },

    // Navigation
    NavigationMenu: {
      description: "Nav menu",
      import: "@/components/ui/navigation-menu",
    },
    Breadcrumb: {
      description: "Breadcrumbs",
      import: "@/components/ui/breadcrumb",
    },
    DropdownMenu: {
      description: "Dropdown menu",
      import: "@/components/ui/dropdown-menu",
    },
    Command: {
      description: "Command palette",
      import: "@/components/ui/command",
    },
  };
}

/**
 * Step 3: Bundle the artifact to a single HTML file
 */
export async function bundleArtifact(
  projectPath: string,
): Promise<BuildResult> {
  try {
    execSync("bash scripts/bundle-artifact.sh", {
      cwd: projectPath,
      stdio: "pipe",
    });

    const bundlePath = path.join(projectPath, "bundle.html");
    const stats = fs.statSync(bundlePath);

    return {
      success: true,
      bundlePath,
      bundleSize: stats.size,
    };
  } catch (error) {
    return {
      success: false,
      errors: [`Bundle failed: ${error}`],
    };
  }
}

/**
 * Get design inspiration and guidelines
 */
export function getDesignGuidelines(): {
  avoid: string[];
  embrace: string[];
  fontSuggestions: string[];
  colorTips: string[];
  animationTips: string[];
} {
  return {
    avoid: [
      "Excessive centered layouts",
      "Purple gradients on white backgrounds",
      "Uniform rounded corners everywhere",
      "Inter, Roboto, Arial fonts (overused)",
      "Clichéd color schemes",
      "Predictable cookie-cutter patterns",
    ],
    embrace: [
      "Distinctive typography choices",
      "Cohesive aesthetic with sharp accents",
      "CSS variables for consistency",
      "Meaningful animations",
      "Atmospheric backgrounds (gradients, patterns)",
      "Unexpected creative choices",
      "Context-specific character",
    ],
    fontSuggestions: [
      "Space Grotesk (geometric sans)",
      "Outfit (modern geometric)",
      "Sora (tech-forward)",
      "Manrope (readable)",
      "Clash Display (bold headlines)",
      "Cabinet Grotesk (editorial)",
      "Satoshi (minimal)",
      "General Sans (versatile)",
      "Plus Jakarta Sans (friendly)",
      "DM Sans (compact)",
    ],
    colorTips: [
      "Dominant color with sharp accents > evenly distributed palette",
      "Draw from IDE themes for developer tools",
      "Consider cultural aesthetics for context",
      "Dark themes: avoid pure black (#000), use rich darks",
      "Light themes: avoid pure white (#fff), use warm/cool tints",
    ],
    animationTips: [
      "Prioritize page load animations with staggered reveals",
      "Use animation-delay for orchestrated effects",
      "Prefer CSS animations over JS when possible",
      "Focus on high-impact moments over scattered micro-interactions",
      "Use Motion library for React when needed",
    ],
  };
}

// =============================================================================
// WORKFLOW
// =============================================================================

/**
 * Complete artifact building workflow
 *
 * Usage:
 * ```typescript
 * import { buildFrontendArtifact } from './.claude/mcp/skills/frontend-artifact-builder';
 *
 * const result = await buildFrontendArtifact({
 *   projectName: 'my-dashboard',
 *   description: 'Analytics dashboard with charts',
 *   components: ['Card', 'Tabs', 'Table', 'Button']
 * });
 * ```
 */
export async function buildFrontendArtifact(config: ArtifactConfig): Promise<{
  success: boolean;
  projectPath?: string;
  bundlePath?: string;
  guidelines: ReturnType<typeof getDesignGuidelines>;
  components: ReturnType<typeof getComponentReference>;
  nextSteps: string[];
}> {
  const guidelines = getDesignGuidelines();
  const components = getComponentReference();

  // Step 1: Initialize
  const initResult = await initArtifact(config);

  if (!initResult.success) {
    return {
      success: false,
      guidelines,
      components,
      nextSteps: ["Fix initialization errors and retry"],
    };
  }

  return {
    success: true,
    projectPath: initResult.projectPath,
    guidelines,
    components,
    nextSteps: [
      `1. cd ${config.projectName}`,
      "2. Edit src/App.tsx with your artifact code",
      "3. Use shadcn/ui components from @/components/ui/*",
      "4. Run: bash scripts/bundle-artifact.sh",
      "5. Share bundle.html as artifact",
    ],
  };
}

// =============================================================================
// DOCUMENTATION
// =============================================================================

export const DOCS = `
# Frontend Artifact Builder

## Quick Start

1. Initialize: bash scripts/init-artifact.sh <project-name>
2. Develop: Edit generated code in src/
3. Bundle: bash scripts/bundle-artifact.sh  
4. Share: Display bundle.html to user

## Stack
- React 18 + TypeScript + Vite
- Tailwind CSS 3.4.1
- shadcn/ui (40+ components)
- Parcel (bundling)

## Design Guidelines (Avoid AI Slop!)
- NO: centered layouts, purple gradients, Inter font, uniform corners
- YES: distinctive fonts, sharp accents, meaningful animations, atmosphere

## shadcn/ui Reference
https://ui.shadcn.com/docs/components
`;
