// Toolbar reconstructed from mainwindow_Init.cpp createToolBars()
// Standard + Decorator on row 1, Edit + Filter + Search on row 2

import { useMeshStore } from '../stores/meshStore';
import type { RenderMode } from './Toolbar';

interface IconToolbarProps {
  onOpenFile: () => void;
  onSave: () => void;
  onShowLayers: () => void;
  onShowStats: () => void;
}

function Btn({ icon, title, onClick, active, disabled, testId }: {
  icon: string; title: string; onClick: () => void; active?: boolean; disabled?: boolean; testId?: string;
}) {
  return (
    <button
      onClick={disabled ? undefined : onClick}
      title={title}
      data-testid={testId}
      data-active={active ? 'true' : 'false'}
      data-disabled={disabled ? 'true' : 'false'}
      style={{
        width: 28, height: 28, padding: 2, border: 'none', borderRadius: 2,
        background: active ? '#b0c4de' : 'transparent', cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.3 : 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}
      onMouseEnter={(e) => { if (!active && !disabled) e.currentTarget.style.background = '#d0d0d0'; }}
      onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
    >
      <img src={`/icons/${icon}`} alt={title} style={{ width: 24, height: 24 }}
        onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
    </button>
  );
}

const Sep = () => <div style={{ width: 1, height: 24, background: '#b0b0b0', margin: '0 2px', flexShrink: 0 }} />;

export function IconToolbar({ onOpenFile, onSave, onShowLayers, onShowStats }: IconToolbarProps) {
  const { state, dispatch } = useMeshStore();
  const rm = state.globalRenderMode;
  const tm = state.toolMode;
  const setMode = (m: RenderMode) => dispatch({ type: 'SET_RENDER_MODE', mode: m });
  const setTool = (m: string) => dispatch({ type: 'SET_TOOL_MODE', mode: m as import('../stores/meshStore').ToolMode });

  return (
    <div style={{ background: '#e8e8e8', borderBottom: '1px solid #c0c0c0', flexShrink: 0 }}>
      <div data-testid="toolbar-row-1" style={{ display: 'flex', alignItems: 'center', height: 32, padding: '0 2px', gap: 0, flexWrap: 'nowrap', overflow: 'hidden' }}>
        {/* Standard ToolBar */}
        <Btn icon="new_project.png" title="New Empty Project (Ctrl+N)" onClick={() => dispatch({ type: 'CLEAR_ALL_LAYERS' })} testId="tb-new-project" />
        <Btn icon="open_project.png" title="Open Project (Ctrl+O)" onClick={onOpenFile} testId="tb-open-project" />
        <Btn icon="import_mesh.png" title="Import Mesh (Ctrl+I)" onClick={onOpenFile} testId="tb-import" />
        <Btn icon="reload.png" title="Reload (Alt+R)" onClick={() => {}} testId="tb-reload" />
        <Btn icon="reload_all.png" title="Reload All (Ctrl+Shift+R)" onClick={() => {}} testId="tb-reload-all" />
        <Btn icon="save.png" title="Export Mesh (Ctrl+E)" onClick={onSave} testId="tb-export" />
        <Btn icon="snapshot.png" title="Save Snapshot" onClick={() => {
          const c = document.querySelector('canvas');
          if (c) c.toBlob(b => { if (b) { const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = 'snapshot.png'; a.click(); }});
        }} testId="tb-snapshot" />
        <Btn icon="layers.png" title="Show Layer Dialog (Ctrl+L)" onClick={onShowLayers} testId="tb-layers" />
        <Btn icon="view_raster.png" title="Show Raster View" onClick={() => {}} disabled testId="tb-raster" />
        <Sep />
        {/* Rendering modes */}
        <Btn icon="bbox.png" title="Bounding Box (B)" onClick={() => dispatch({ type: 'TOGGLE_BBOX' })} active={state.showBBox} testId="toggle-bbox" />
        <Btn icon="points.png" title="Points" onClick={() => setMode('points')} active={rm === 'points'} testId="mode-points" />
        <Btn icon="wire.png" title="Wireframe (3)" onClick={() => setMode('wireframe')} active={rm === 'wireframe'} testId="mode-wireframe" />
        <Btn icon="smooth.png" title="Smooth (2)" onClick={() => setMode('solid')} active={rm === 'solid'} testId="mode-solid" />
        <Btn icon="flat.png" title="Flat" onClick={() => setMode('flat')} active={rm === 'flat'} testId="mode-flat" />
        <Sep />
        {/* Decorators */}
        <Btn icon="selected_face.png" title="Show Selected Faces" onClick={() => {}} testId="tb-show-sel-face" />
        <Btn icon="selected_vert.png" title="Show Selected Vertices" onClick={() => {}} testId="tb-show-sel-vert" />
        <Btn icon="show_axis.png" title="Show Axis" onClick={() => {}} testId="tb-show-axis" />
        <Btn icon="show_boundary.png" title="Show Boundary Edges" onClick={() => dispatch({ type: 'SET_RENDER_SETTING', key: 'showBoundary', value: !state.showBoundary })} active={state.showBoundary} testId="tb-show-boundary" />
        <Btn icon="show_nonmanifold_edge.png" title="Show Non-Manifold Edges" onClick={() => dispatch({ type: 'SET_RENDER_SETTING', key: 'showNonManifold', value: !state.showNonManifold })} active={state.showNonManifold} testId="tb-show-nm-edge" />
        <Btn icon="show_nonmanifold_vertex.png" title="Show Non-Manifold Vertices" onClick={() => dispatch({ type: 'SET_RENDER_SETTING', key: 'showNonManifold', value: !state.showNonManifold })} testId="tb-show-nm-vert" />
        <Btn icon="show_background_grid.png" title="Show Grid (G)" onClick={() => dispatch({ type: 'TOGGLE_GRID' })} active={state.showGrid} testId="toggle-grid" />
        <Btn icon="lighton.png" title="SSAO Lighting" onClick={() => dispatch({ type: 'SET_RENDER_SETTING', key: 'ssaoEnabled', value: !state.ssaoEnabled })} active={state.ssaoEnabled} testId="toggle-ssao" />
        <Sep />
        {/* Edit ToolBar (mainwindow_Init.cpp L520-530, plugin order from edit_*_factory.cpp) */}
        <Btn icon="no_edit.png" title="Not Editing (Esc)" onClick={() => setTool('navigate')} active={tm === 'navigate'} testId="tool-navigate" />
        <Sep />
        {/* edit_select: 4 actions */}
        <Btn icon="select_face.png" title="Select Faces in Region (Q)" onClick={() => setTool('select_rect')} active={tm === 'select_rect'} testId="tool-select_rect" />
        <Btn icon="select_face_connected.png" title="Select Connected Components (E)" onClick={() => setTool('select_click')} active={tm === 'select_click'} testId="tool-select_click" />
        <Btn icon="select_vertex.png" title="Select Vertices (W)" onClick={() => setTool('select_brush')} active={tm === 'select_brush'} testId="tool-select_brush" />
        <Btn icon="select_area.png" title="Select in Polyline Area" onClick={() => setTool('select_rect')} testId="tool-select-area" />
        {/* edit_align */}
        <Btn icon="icon_align.png" title="Align Tool (A)" onClick={() => setTool('align')} active={tm === 'align'} testId="tb-align" />
        {/* edit_manipulators */}
        <Btn icon="icon_manipulators.png" title="Manipulators Tool" onClick={() => setTool('manipulator')} active={tm === 'manipulator'} testId="tb-manipulators" />
        {/* edit_measure */}
        <Btn icon="icon_measure.png" title="Measuring Tool (R)" onClick={() => setTool('measure_distance')} active={tm === 'measure_distance'} testId="tool-measure-distance" />
        {/* edit_mutualcorrs */}
        <Btn icon="icon_mutualcorrs.png" title="Raster Alignment" onClick={() => {}} disabled testId="tb-mutualcorrs" />
        {/* edit_paint */}
        <Btn icon="paintbrush-22.png" title="Z-Painting" onClick={() => setTool('paint')} active={tm === 'paint'} testId="tb-paint" />
        {/* edit_pickpoints */}
        <Btn icon="pickpoints.png" title="Pick Points" onClick={() => setTool('pickpoints')} active={tm === 'pickpoints'} testId="tb-pickpoints" />
        {/* edit_point */}
        <Btn icon="select_vertex_geodesic.png" title="Select Vertex Clusters" onClick={() => {}} testId="tb-vertex-geodesic" />
        <Btn icon="select_vertex_plane.png" title="Select Vertices on Plane" onClick={() => {}} testId="tb-vertex-plane" />
        {/* edit_quality */}
        <Btn icon="qualitymapper.png" title="Quality Mapper" onClick={() => {}} testId="tb-quality" />
        {/* edit_referencing */}
        <Btn icon="icon_referencing.png" title="Reference Scene" onClick={() => {}} testId="tb-referencing" />
        {/* edit_sample */}
        <Btn icon="icon_info.png" title="Get Info" onClick={onShowStats} testId="tb-info" />
        <Sep />
        {/* Filter selection actions */}
        <Btn icon="sel_all.png" title="Select All (Ctrl+A)" onClick={() => {}} testId="tb-sel-all" />
        <Btn icon="sel_none.png" title="Select None (Ctrl+D)" onClick={() => {}} testId="tb-sel-none" />
        <Btn icon="sel_inv.png" title="Invert Selection" onClick={() => {}} testId="tb-sel-inv" />
        <Btn icon="sel_plus.png" title="Expand Selection" onClick={() => {}} testId="tb-sel-plus" />
        <Btn icon="sel_minus.png" title="Shrink Selection" onClick={() => {}} testId="tb-sel-minus" />
        <Btn icon="delete_vert.png" title="Delete Selected Vertices" onClick={() => {}} testId="tb-del-vert" />
        <Btn icon="delete_face.png" title="Delete Selected Faces" onClick={() => {}} testId="tb-del-face" />
        <Btn icon="delete_facevert.png" title="Delete Face with Selected Vertices" onClick={() => {}} testId="tb-del-facevert" />
        <Sep />
        {/* Search (right-aligned) */}
        <div style={{ flex: 1 }} />
        <Btn icon="search.png" title="Search Filters (Ctrl+F)" onClick={() => {
          const input = document.querySelector('[data-testid="filter-search-input"]') as HTMLInputElement;
          if (input) { input.focus(); input.click(); }
        }} testId="tb-search" />
      </div>
    </div>
  );
}
