// Complete MeshLab desktop menu structure derived from mainwindow_Init.cpp
// Filters derived from meshlabplugins/filter_*/ source code

import type { MenuItem } from '../components/MenuBar';

// Set of filter IDs that are implemented in our Web version
const IMPLEMENTED_FILTERS = new Set([
  // Smoothing
  'laplacian_smooth', 'taubin_smooth', 'hc_laplacian_smooth',
  'scale_dependent_smooth', 'two_step_smooth', 'depth_smooth',
  'unsharp_mask_geometry', 'unsharp_mask_normals', 'unsharp_mask_quality',
  'smooth_face_normals', 'smooth_vertex_quality', 'linear_morph',
  // Remeshing
  'simplification', 'subdivision', 'loop_subdivision', 'butterfly_subdivision',
  'catmull_clark_subdivision', 'isotropic_remeshing', 'clustering_decimation',
  'marching_cubes', 'screened_poisson', 'ball_pivoting', 'surface_reconstruction_vcg',
  // Cleaning
  'remove_duplicate_vertices', 'remove_unreferenced_vertices', 'remove_duplicate_faces',
  'remove_degenerate_faces', 'remove_t_vertices', 'snap_mismatched_borders',
  'merge_close_vertices', 'merge_wedge_texture_coord', 'remove_isolated_folded_faces',
  'fix_non_manifold_edges', 'repair_non_manifold_vertices', 'auto_repair',
  'fill_holes', 'remove_small_components', 'remove_flipped_faces',
  // Transform
  'scale', 'translate', 'rotate',
  // Normals
  'compute_normals', 'recompute_vertex_normals', 'normalize_face_normals',
  'normalize_vertex_normals', 'invert_faces', 'estimate_normals',
  'normal_extrapolation', 'normal_smoothing_point_cloud', 'principal_curvature_direction',
  // Color
  'vertex_color_fill', 'vertex_color_invert', 'vertex_color_brightness_contrast_gamma',
  'vertex_color_levels', 'vertex_color_colourisation', 'vertex_color_desaturation',
  'vertex_color_white_balance', 'perlin_color', 'color_noise',
  'smooth_vertex_colors', 'smooth_face_colors',
  'colorize_gaussian_curvature', 'colorize_mean_curvature', 'color_from_quality',
  'colorize_principal_k1', 'colorize_principal_k2', 'colorize_shape_index',
  'discrete_curvatures', 'random_face_color',
  'vertex_color_from_face', 'face_color_from_vertex',
  // Quality
  'compute_topological_measures', 'compute_geometric_measures',
  'compute_selection_area_perimeter',
  'per_vertex_quality_statistics', 'per_face_quality_statistics',
  'per_vertex_quality_histogram',
  // Selection
  'select_all_filter', 'select_none_filter', 'select_connected_faces',
  'select_by_vertex_quality', 'select_by_face_quality',
  'select_by_color_range', 'invert_selection_filter',
  'select_border', 'select_by_dihedral_angle', 'select_ugly_faces',
  'select_non_manifold_faces', 'select_non_manifold_vertices',
  'select_self_intersecting', 'erode_selection', 'dilate_selection',
  'delete_selected_vertices', 'delete_selected_faces_filter', 'delete_all_faces',
  'delete_face_with_selected_vertices',
  // Texture
  'parametrize_trivial', 'uv_checker_pattern', 'voronoi_atlas',
  'basic_triangle_mapping', 'planar_mapping', 'color_to_texture',
  'set_texture', 'uv_wedge_to_vertex', 'uv_vertex_to_wedge', 'texture_defragmentation',
  // Alignment
  'freeze_transform', 'reset_transform', 'align_icp',
  // Reconstruction
  // Sampling
  'montecarlo_sampling', 'poisson_disk_sampling', 'hausdorff_distance',
  'clustered_vertex_sampling', 'mesh_element_subsampling',
  'stratified_triangle_sampling', 'texel_sampling', 'uniform_mesh_resampling',
  'voronoi_vertex_coloring', 'distance_from_reference_mesh',
  // Mesh Creation
  'create_box', 'create_sphere', 'create_torus', 'create_cone', 'create_plane',
  'create_icosahedron', 'create_tetrahedron', 'create_octahedron',
  'create_dodecahedron', 'create_annulus', 'create_sphere_cap', 'create_points_on_sphere',
  // Layer
  'split_connected_components', 'flatten_visible_layers',
  'duplicate_layer', 'delete_current_mesh', 'move_selected_to_new_layer', 'rename_mesh',
  // Boolean / Other
  'mesh_boolean', 'convex_hull', 'alpha_complex_shape',
  'voronoi_scaffolding', 'ambient_occlusion',
  // Camera
  'set_mesh_camera', 'set_raster_camera',
  // Point Set
  'point_cloud_simplification', 'estimate_radius_from_density',
  // Range Map
  'ball_pivoting_range_map',
]);

function f(label: string, webId?: string): MenuItem {
  const implemented = webId ? IMPLEMENTED_FILTERS.has(webId) : false;
  return {
    label: implemented && webId ? `${label}...` : label,
    action: webId ? `filter:${webId}` : undefined,
    disabled: !implemented,
  };
}

export const DESKTOP_FILTERS_MENU: MenuItem[] = [
  { label: 'Selection', children: [
    f('Select All', 'select_all_filter'), f('Select None', 'select_none_filter'),
    f('Select Connected Faces', 'select_connected_faces'),
    f('Select by Vertex Quality', 'select_by_vertex_quality'),
    f('Select by Face Quality', 'select_by_face_quality'),
    f('Select by Color Range', 'select_by_color_range'), f('Invert Selection', 'invert_selection_filter'),
    f('Select Border', 'select_border'), f('Select by Dihedral Angle', 'select_by_dihedral_angle'),
    f('Select Ugly Faces', 'select_ugly_faces'),
    f('Select Non-Manifold Faces', 'select_non_manifold_faces'),
    f('Select Non-Manifold Vertices', 'select_non_manifold_vertices'),
    f('Select by Self-Intersection', 'select_self_intersecting'),
    f('Erode Selection', 'erode_selection'), f('Dilate Selection', 'dilate_selection'),
    f('Delete Selected Vertices', 'delete_selected_vertices'),
    f('Delete Selected Faces', 'delete_selected_faces_filter'),
    f('Delete All Faces', 'delete_all_faces'),
    f('Delete Face with Selected Vertices', 'delete_face_with_selected_vertices'),
  ]},
  { label: 'Cleaning and Repairing', children: [
    f('Remove Duplicate Vertices', 'remove_duplicate_vertices'),
    f('Remove Unreferenced Vertices', 'remove_unreferenced_vertices'),
    f('Remove Duplicate Faces', 'remove_duplicate_faces'),
    f('Remove Zero Area Faces', 'remove_degenerate_faces'),
    f('Remove T-Vertices', 'remove_t_vertices'),
    f('Snap Mismatched Borders', 'snap_mismatched_borders'),
    f('Merge Close Vertices', 'merge_close_vertices'),
    f('Merge Wedge Texture Coord', 'merge_wedge_texture_coord'),
    f('Remove Isolated Folded Faces', 'remove_isolated_folded_faces'),
    f('Repair Non-Manifold Edges', 'fix_non_manifold_edges'),
    f('Repair Non-Manifold Vertices', 'repair_non_manifold_vertices'),
    f('Auto-Repair All', 'auto_repair'),
    f('Fill Holes', 'fill_holes'), f('Remove Small Components', 'remove_small_components'),
    f('Remove Flipped Faces', 'remove_flipped_faces'),
  ]},
  { label: 'Remeshing, Simplification and Reconstruction', children: [
    f('Quadric Edge Collapse Decimation', 'simplification'),
    f('Midpoint Subdivision', 'subdivision'),
    f('Loop Subdivision', 'loop_subdivision'), f('Butterfly Subdivision', 'butterfly_subdivision'),
    f('Catmull-Clark Subdivision', 'catmull_clark_subdivision'),
    f('Explicit Isotropic Remeshing', 'isotropic_remeshing'),
    f('Clustering Decimation', 'clustering_decimation'),
    f('Marching Cubes Reconstruction', 'marching_cubes'),
    f('Screened Poisson Reconstruction', 'screened_poisson'),
    f('Ball Pivoting Surface Reconstruction', 'ball_pivoting'),
    f('Surface Reconstruction: VCG', 'surface_reconstruction_vcg'),
  ]},
  { label: 'Smoothing, Fairing and Deformation', children: [
    f('Laplacian Smooth', 'laplacian_smooth'), f('HC Laplacian Smooth', 'hc_laplacian_smooth'),
    f('Taubin Smooth', 'taubin_smooth'), f('Scale Dependent Laplacian Smooth', 'scale_dependent_smooth'),
    f('Two Step Smooth', 'two_step_smooth'), f('Depth Smooth', 'depth_smooth'),
    f('UnSharp Mask Geometry', 'unsharp_mask_geometry'),
    f('UnSharp Mask Normals', 'unsharp_mask_normals'),
    f('UnSharp Mask Quality', 'unsharp_mask_quality'),
    f('Smooth Face Normals', 'smooth_face_normals'),
    f('Smooth Vertex Quality', 'smooth_vertex_quality'),
    f('Linear Morph between meshes', 'linear_morph'),
  ]},
  { label: 'Color Creation and Processing', children: [
    f('Vertex Color Fill', 'vertex_color_fill'), f('Vertex Color Invert', 'vertex_color_invert'),
    f('Vertex Color Brightness Contrast Gamma', 'vertex_color_brightness_contrast_gamma'),
    f('Vertex Color Levels', 'vertex_color_levels'),
    f('Vertex Color Colourisation', 'vertex_color_colourisation'),
    f('Vertex Color Desaturation', 'vertex_color_desaturation'),
    f('Vertex Color White Balance', 'vertex_color_white_balance'),
    f('Perlin Color', 'perlin_color'), f('Color Noise', 'color_noise'),
    f('Smooth Vertex Colors', 'smooth_vertex_colors'),
    f('Smooth Face Colors', 'smooth_face_colors'),
    f('Colorize by Gaussian Curvature', 'colorize_gaussian_curvature'),
    f('Colorize by Mean Curvature', 'colorize_mean_curvature'),
    f('Quality to Vertex Color', 'color_from_quality'),
    f('Colorize Principal Curvature (k1)', 'colorize_principal_k1'),
    f('Colorize Principal Curvature (k2)', 'colorize_principal_k2'),
    f('Colorize Shape Index', 'colorize_shape_index'),
    f('Discrete Curvatures', 'discrete_curvatures'),
    f('Random Face Color', 'random_face_color'),
    f('Vertex Color from Face', 'vertex_color_from_face'),
    f('Face Color from Vertex', 'face_color_from_vertex'),
  ]},
  { label: 'Quality Measure and Computations', children: [
    f('Compute Topological Measures', 'compute_topological_measures'),
    f('Compute Geometric Measures', 'compute_geometric_measures'),
    f('Compute Area/Perimeter of Selection', 'compute_selection_area_perimeter'),
    f('Per Vertex Quality Statistics', 'per_vertex_quality_statistics'),
    f('Per Face Quality Statistics', 'per_face_quality_statistics'),
    f('Per Vertex Quality Histogram', 'per_vertex_quality_histogram'),
  ]},
  { label: 'Normals, Curvatures and Orientation', children: [
    f('Recompute Face Normals', 'compute_normals'),
    f('Recompute Vertex Normals', 'recompute_vertex_normals'),
    f('Normalize Face Normals', 'normalize_face_normals'),
    f('Normalize Vertex Normals', 'normalize_vertex_normals'),
    f('Invert Faces Orientation', 'invert_faces'),
    f('Estimate Normals for Point Sets', 'estimate_normals'),
    f('Normal Extrapolation', 'normal_extrapolation'),
    f('Normal Smoothing (Point Cloud)', 'normal_smoothing_point_cloud'),
    f('Principal Curvature Direction', 'principal_curvature_direction'),
  ]},
  { label: 'Mesh Layer', children: [
    f('Flatten Visible Layers', 'flatten_visible_layers'),
    f('Duplicate Current Layer', 'duplicate_layer'),
    f('Delete Current Mesh', 'delete_current_mesh'),
    f('Split in Connected Components', 'split_connected_components'),
    f('Move Selected Faces to Another Layer', 'move_selected_to_new_layer'),
    f('Rename Current Mesh', 'rename_mesh'),
  ]},
  { label: 'Sampling', children: [
    f('Poisson-disk Sampling', 'poisson_disk_sampling'),
    f('Montecarlo Sampling', 'montecarlo_sampling'),
    f('Clustered Vertex Sampling', 'clustered_vertex_sampling'),
    f('Hausdorff Distance', 'hausdorff_distance'),
    f('Mesh Element Subsampling', 'mesh_element_subsampling'),
    f('Stratified Triangle Sampling', 'stratified_triangle_sampling'),
    f('Texel Sampling', 'texel_sampling'),
    f('Uniform Mesh Resampling', 'uniform_mesh_resampling'),
    f('Voronoi Vertex Coloring', 'voronoi_vertex_coloring'),
    f('Distance from Reference Mesh', 'distance_from_reference_mesh'),
  ]},
  { label: 'Texture', children: [
    f('Trivial Per-Triangle UV', 'parametrize_trivial'),
    f('Apply Checker Pattern', 'uv_checker_pattern'),
    f('Voronoi Atlas', 'voronoi_atlas'),
    f('Basic Triangle Mapping', 'basic_triangle_mapping'),
    f('Planar Mapping', 'planar_mapping'),
    f('Color to Texture', 'color_to_texture'), f('Set Texture', 'set_texture'),
    f('UV Wedge to Vertex', 'uv_wedge_to_vertex'),
    f('UV Vertex to Wedge', 'uv_vertex_to_wedge'),
    f('Texture Defragmentation', 'texture_defragmentation'),
  ]},
  { label: 'Create New Mesh Layer', children: [
    f('Box/Cube', 'create_box'), f('Sphere', 'create_sphere'),
    f('Icosahedron', 'create_icosahedron'), f('Torus', 'create_torus'),
    f('Cone', 'create_cone'), f('Annulus', 'create_annulus'),
    f('Sphere Cap', 'create_sphere_cap'), f('Tetrahedron', 'create_tetrahedron'),
    f('Octahedron', 'create_octahedron'), f('Dodecahedron', 'create_dodecahedron'),
    f('Plane', 'create_plane'), f('Points on a Sphere', 'create_points_on_sphere'),
  ]},
  { label: 'Camera', children: [
    f('Set Mesh Camera', 'set_mesh_camera'), f('Set Raster Camera', 'set_raster_camera'),
  ]},
  { label: 'Point Set', children: [
    f('Point Cloud Simplification', 'point_cloud_simplification'),
    f('Estimate radius from density', 'estimate_radius_from_density'),
  ]},
  { label: 'Range Map', children: [
    f('Surface Reconstruction: Ball Pivoting', 'ball_pivoting_range_map'),
  ]},
  { label: 'Other', children: [
    f('Mesh Boolean (CSG)', 'mesh_boolean'), f('Convex Hull', 'convex_hull'),
    f('Alpha Complex/Shape', 'alpha_complex_shape'),
    f('Voronoi Scaffolding', 'voronoi_scaffolding'),
    f('Ambient Occlusion', 'ambient_occlusion'),
  ]},
];

export const DESKTOP_FILE_MENU: MenuItem[] = [
  { label: 'New Empty Project...', shortcut: 'Ctrl+N', action: 'newProject' },
  { label: 'Open Project...', shortcut: 'Ctrl+O', action: 'openFile' },
  { label: 'Append Project to Current...', action: 'openFile' },
  { label: 'Save Project As...', shortcut: 'Ctrl+S', action: 'exportOBJ' },
  { label: 'Close Project', action: 'newProject' },
  { type: 'separator' },
  { label: 'Import Mesh...', shortcut: 'Ctrl+I', action: 'openFile' },
  { label: 'Export Mesh...', shortcut: 'Ctrl+E', action: 'exportOBJ' },
  { label: 'Export Mesh As...', children: [
    { label: 'OBJ (.obj)', action: 'exportOBJ' },
    { label: 'STL (.stl)', action: 'exportSTL' },
    { label: 'PLY (.ply)', action: 'exportPLY' },
    { label: 'OFF (.off)', action: 'exportOFF' },
    { label: 'GLB (.glb)', action: 'exportGLB' },
    { label: 'WRL (.wrl)', action: 'exportWRL' },
    { label: 'DXF (.dxf)', action: 'exportDXF' },
    { label: 'USDA (.usda)', action: 'exportUSDA' },
    { label: 'USDZ (.usdz)', action: 'exportUSDZ' },
  ]},
  { label: 'Reload', shortcut: 'Alt+R', action: 'reload' },
  { label: 'Reload All', shortcut: 'Ctrl+Shift+R', action: 'reload' },
  { type: 'separator' },
  { label: 'Import Raster...', disabled: true },
  { type: 'separator' },
  { label: 'Save Snapshot', action: 'snapshot' },
  { type: 'separator' },
  { label: 'Exit', shortcut: 'Ctrl+Q', action: 'newProject' },
];

export const DESKTOP_EDIT_MENU: MenuItem[] = [
  { label: 'Undo', shortcut: 'Ctrl+Z', action: 'undo' },
  { label: 'Redo', shortcut: 'Ctrl+Shift+Z', action: 'redo' },
  { type: 'separator' },
  { label: 'Select All', shortcut: 'Ctrl+A', action: 'selectAll' },
  { label: 'Deselect All', shortcut: 'Ctrl+D', action: 'deselectAll' },
  { label: 'Invert Selection', action: 'invertSelection' },
  { label: 'Delete Selected', shortcut: 'Delete', action: 'deleteSelected' },
  { type: 'separator' },
  { label: 'Preferences...', action: 'preferences' },
];

export const DESKTOP_RENDER_MENU: MenuItem[] = [
  { label: 'Bounding Box', shortcut: 'B', action: 'toggle:bbox', type: 'checkbox' },
  { label: 'Points', action: 'mode:points', type: 'radio' },
  { label: 'Wire', action: 'mode:wireframe', type: 'radio' },
  { label: 'Flat', action: 'mode:flat', type: 'radio' },
  { label: 'Smooth', action: 'mode:solid', type: 'radio' },
  { type: 'separator' },
  { label: 'Show Grid', shortcut: 'G', action: 'toggle:grid', type: 'checkbox' },
  { label: 'Show Axis', action: 'toggle:axis', type: 'checkbox' },
  { label: 'Show Crease Edges', action: 'toggle:edges', type: 'checkbox' },
  { type: 'separator' },
  { label: 'SSAO', action: 'toggle:ssao', type: 'checkbox' },
  { label: 'Shadows', action: 'toggle:shadows', type: 'checkbox' },
  { label: 'Clipping Plane...', action: 'clippingSettings' },
  { type: 'separator' },
  { label: 'Matcap', children: [
    { label: 'Clay', action: 'matcap:default' },
    { label: 'Metal', action: 'matcap:metal' },
    { label: 'Ceramic', action: 'matcap:ceramic' },
    { label: 'Red Wax', action: 'matcap:red_wax' },
    { label: 'Blue Rim', action: 'matcap:blue_rim' },
    { label: 'X-Ray', action: 'matcap:xray' },
  ]},
  { type: 'separator' },
  { label: 'Show Normals', action: 'toggle:normals', type: 'checkbox' },
  { label: 'Show Boundary', action: 'toggle:boundary', type: 'checkbox' },
  { label: 'Show Non-Manifold Edges', action: 'toggle:nonmanifold', type: 'checkbox' },
  { label: 'Show Non-Manifold Vertices', action: 'toggle:nonmanifold', type: 'checkbox' },
  { type: 'separator' },
  { label: 'Background Color...', action: 'bgColor' },
];

export const DESKTOP_VIEW_MENU: MenuItem[] = [
  { label: 'Fullscreen', shortcut: 'Alt+Return', action: 'fullscreen' },
  { type: 'separator' },
  { label: 'Show Layer Dialog', shortcut: 'Ctrl+L', action: 'toggle:layerDialog', type: 'checkbox' },
  { label: 'Show Script Panel', action: 'toggle:scriptPanel', type: 'checkbox' },
  { type: 'separator' },
  { label: 'Fit to View', shortcut: 'Home', action: 'fitToView' },
  { label: 'Show Trackball', shortcut: 'Shift+H', action: 'toggle:trackball', type: 'checkbox' },
  { label: 'Reset Trackball', shortcut: 'Ctrl+H', action: 'resetCamera' },
  { type: 'separator' },
  { label: 'Toggle Orthographic Camera', action: 'toggle:ortho' },
  { type: 'separator' },
  { label: 'View From', children: [
    { label: 'Front', action: 'viewFrom:front' }, { label: 'Back', action: 'viewFrom:back' },
    { label: 'Right', action: 'viewFrom:right' }, { label: 'Left', action: 'viewFrom:left' },
    { label: 'Top', action: 'viewFrom:top' }, { label: 'Bottom', action: 'viewFrom:bottom' },
  ]},
  { type: 'separator' },
  { label: 'Split View Horizontally', action: 'splitH' },
  { label: 'Split View Vertically', action: 'splitV' },
];

export const DESKTOP_TOOLS_MENU: MenuItem[] = [
  { label: 'Navigate', shortcut: 'Esc', action: 'tool:navigate', type: 'radio' },
  { type: 'separator' },
  { label: 'Rect Select', shortcut: 'Q', action: 'tool:select_rect', type: 'radio' },
  { label: 'Brush Select', shortcut: 'W', action: 'tool:select_brush', type: 'radio' },
  { label: 'Component Select', shortcut: 'E', action: 'tool:select_click', type: 'radio' },
  { type: 'separator' },
  { label: 'Measure Distance', shortcut: 'R', action: 'tool:measure_distance', type: 'radio' },
  { label: 'Measure Angle', shortcut: 'T', action: 'tool:measure_angle', type: 'radio' },
  { type: 'separator' },
  { label: 'Alignment Tool...', shortcut: 'A', action: 'tool:align' },
  { label: 'Paint Tool', action: 'tool:paint' },
  { label: 'Pick Points', action: 'tool:pickpoints' },
  { label: 'Manipulators', action: 'tool:manipulator' },
  { type: 'separator' },
  { label: 'Options...', action: 'preferences' },
];

export const DESKTOP_HELP_MENU: MenuItem[] = [
  { label: 'About MeshLab Web', action: 'about' },
  { label: 'Plugin Info', action: 'pluginInfo' },
  { label: 'Online Documentation', action: 'onlineDocs' },
  { label: 'Keyboard Shortcuts', action: 'shortcuts' },
  { label: 'Submit Bug', action: 'submitBug' },
  { label: 'Check for Updates', action: 'checkUpdates' },
];

export function buildDesktopMenus(): Record<string, MenuItem[]> {
  return {
    File: DESKTOP_FILE_MENU,
    Edit: DESKTOP_EDIT_MENU,
    Filters: [
      { label: 'Apply Last Filter', shortcut: 'Ctrl+P', action: 'applyLastFilter' },
      { label: 'Show Current Filter Script', action: 'toggle:scriptPanel' },
      { label: 'Mesh Statistics...', action: 'meshStats' },
      { type: 'separator' },
      ...DESKTOP_FILTERS_MENU,
    ],
    Render: DESKTOP_RENDER_MENU,
    View: DESKTOP_VIEW_MENU,
    Windows: [
      { label: 'Close All Windows', action: 'newProject' },
      { type: 'separator' },
      { label: 'Tile', action: 'splitH' },
      { label: 'Cascade', action: 'fitToView' },
      { label: 'Next', action: 'fitToView' },
      { type: 'separator' },
      { label: 'Split current view', children: [
        { label: 'Horizontally', action: 'splitH' },
        { label: 'Vertically', action: 'splitV' },
      ]},
      { label: 'Close current view', action: 'fitToView' },
      { label: 'Link Viewers', action: 'toggle:linkViewers', type: 'checkbox' as const },
      { type: 'separator' },
      { label: 'View from', children: [
        { label: 'Front', action: 'viewFrom:front' }, { label: 'Back', action: 'viewFrom:back' },
        { label: 'Right', action: 'viewFrom:right' }, { label: 'Left', action: 'viewFrom:left' },
        { label: 'Top', action: 'viewFrom:top' }, { label: 'Bottom', action: 'viewFrom:bottom' },
      ]},
      { type: 'separator' },
      { label: 'Read camera settings from file', action: 'openFile' },
      { label: 'Save camera settings to file', action: 'exportOBJ' },
    ],
    Tools: DESKTOP_TOOLS_MENU,
    Help: DESKTOP_HELP_MENU,
  };
}
