<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>מערכת מלאה לשרטוט ותכנון מטבחים</title>
  <script src="https://unpkg.com/konva@9/konva.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
  <style>
    body {
      margin: 0;
      padding: 10px;
      font-family: Arial, sans-serif;
      background-color: #f0f2f5;
    }
    .toolbar {
      display: flex;
      gap: 8px;
      margin-bottom: 15px;
      background: #ffffff;
      padding: 10px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      flex-wrap: wrap;
    }
    .btn {
      background-color: #0055b3;
      color: white;
      border: none;
      padding: 8px 12px;
      border-radius: 5px;
      cursor: pointer;
      font-weight: bold;
      font-size: 13px;
    }
    .btn-save { background-color: #2e7d32; }
    .btn-load { background-color: #ed6c02; }
    .btn-export { background-color: #6a1b9a; }
    .btn-delete { background-color: #d32f2f; width: 100%; margin-top: 10px; }
    
    .main-layout {
      display: flex;
      flex-direction: column;
      gap: 15px;
      margin-bottom: 20px;
    }
    #canvas-container {
      width: 100%;
      height: 350px;
      border: 2px solid #333;
      background-color: #ffffff;
      border-radius: 8px;
      box-sizing: border-box;
    }
    #3d-container {
      width: 100%;
      height: 300px;
      border: 2px solid #333;
      background-color: #111;
      border-radius: 8px;
      box-sizing: border-box;
    }
    .inspector-panel {
      width: 100%;
      background: #ffffff;
      padding: 15px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      border: 1px solid #ccc;
      box-sizing: border-box;
    }
    .inspector-panel h3, .bom-panel h3 {
      margin-top: 0;
      color: #333;
      border-bottom: 2px solid #0055b3;
      padding-bottom: 5px;
    }
    .prop-group { margin-bottom: 12px; }
    .prop-group label { display: block; font-size: 13px; color: #555; margin-bottom: 4px; }
    .prop-group input { width: 100%; padding: 6px; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; }
    
    .bom-panel {
      background: #ffffff;
      padding: 15px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      border: 1px solid #ccc;
      overflow-x: auto;
    }
    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    th, td { border: 1px solid #ddd; padding: 8px; text-align: right; font-size: 13px; }
    th { background-color: #f2f2f2; }
    .summary-box { margin-top: 10px; font-weight: bold; color: #0055b3; font-size: 14px; }

    @media (min-width: 768px) {
      .main-layout { flex-direction: row; }
      #canvas-container { flex: 1; height: 450px; }
      #3d-container { flex: 1; height: 450px; }
      .inspector-panel { width: 220px; }
    }
  </style>
</head>
<body>

  <h2>שרטוט ותכנון מטבחים</h2>
  
  <div class="toolbar">
    <button class="btn" onclick="addCabinet(600, 600, 'ארון בסיס 60', '#e6f2ff', '#0055b3')">+ ארון 60</button>
    <button class="btn" onclick="addCabinet(800, 600, 'ארון בסיס 80', '#e6f2ff', '#0055b3')">+ ארון 80</button>
    <button class="btn btn-save" onclick="saveProject()">💾 שמור</button>
    <button class="btn btn-load" onclick="document.getElementById('file-input').click()">📂 טען</button>
    <button class="btn btn-export" onclick="exportImage()">🖼️ תמונה</button>
    <input type="file" id="file-input" style="display: none;" accept=".json" onchange="loadProject(event)">
  </div>

  <div class="main-layout">
    <div id="canvas-container"></div>
    <div id="3d-container"></div>
    
    <div class="inspector-panel">
      <h3>מאפייני ארון</h3>
      <div id="inspector-content">
        <p style="color: #888;">לחץ על ארון בשרטוט כדי להציג פרטים.</p>
      </div>
    </div>
  </div>

  <div class="bom-panel">
    <h3>📋 דוח חלקים (BOM)</h3>
    <table>
      <thead>
        <tr>
          <th>שם רכיב</th>
          <th>רוחב (מ"מ)</th>
          <th>עומק (מ"מ)</th>
          <th>שטח פלטה (מ"ר)</th>
        </tr>
      </thead>
      <tbody id="bom-body">
        <tr><td colspan="4" style="text-align: center; color: #888;">אין ארונות בשרטוט</td></tr>
      </tbody>
    </table>
    <div id="bom-summary" class="summary-box"></div>
  </div>

  <script>
    const container = document.getElementById('canvas-container');
    const stageWidth = container.offsetWidth;
    const stageHeight = container.offsetHeight;
    const GRID_SIZE = 20, SCALE = 0.5;

    let selectedCabinet = null;
    let allCabinets = [];

    const stage = new Konva.Stage({ container: 'canvas-container', width: stageWidth, height: stageHeight });
    const gridLayer = new Konva.Layer(), mainLayer = new Konva.Layer(), uiLayer = new Konva.Layer();
    stage.add(gridLayer); stage.add(mainLayer); stage.add(uiLayer);

    function drawGrid() {
      for (let i = 0; i < stageWidth / GRID_SIZE; i++) gridLayer.add(new Konva.Line({ points: [i * GRID_SIZE, 0, i * GRID_SIZE, stageHeight], stroke: '#e8e8e8' }));
      for (let j = 0; j < stageHeight / GRID_SIZE; j++) gridLayer.add(new Konva.Line({ points: [0, j * GRID_SIZE, stageWidth, j * GRID_SIZE], stroke: '#e8e8e8' }));
      gridLayer.draw();
    }
    drawGrid();

    const container3D = document.getElementById('3d-container');
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xf0f0f0);

    const camera = new THREE.PerspectiveCamera(45, container3D.offsetWidth / container3D.offsetHeight, 1, 10000);
    camera.position.set(0, 1000, 1500);
    camera.lookAt(0, 0, 0);

    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(container3D.offsetWidth, container3D.offsetHeight);
    container3D.appendChild(renderer.domElement);

    const ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
    scene.add(ambientLight);
    const dirLight = new THREE.DirectionalLight(0xffffff, 0.5);
    dirLight.position.set(200, 500, 300);
    scene.add(dirLight);

    const floor = new THREE.Mesh(new THREE.PlaneGeometry(2000, 2000), new THREE.MeshStandardMaterial({ color: 0xdddddd }));
    floor.rotation.x = -Math.PI / 2;
    scene.add(floor);

    let meshes3D = [];

    function update3DView() {
      meshes3D.forEach(m => scene.remove(m));
      meshes3D = [];

      allCabinets.forEach(cab => {
        const info = cab.userData;
        const width = info.width;
        const depth = info.depth;
        const height = 720;

        const geometry = new THREE.BoxGeometry(width, height, depth);
        const material = new THREE.MeshStandardMaterial({ color: 0x0055b3 });
        const mesh = new THREE.Mesh(geometry, material);

        mesh.position.x = cab.x() - stageWidth / 2;
        mesh.position.z = cab.y() - stageHeight / 2;
        mesh.position.y = height / 2;

        scene.add(mesh);
        meshes3D.push(mesh);
      });

      renderer.render(scene, camera);
    }

    function handleSnap(draggedGroup) {
      let x = Math.round(draggedGroup.x() / GRID_SIZE) * GRID_SIZE;
      let y = Math.round(draggedGroup.y() / GRID_SIZE) * GRID_SIZE;
      draggedGroup.position({ x, y });
    }

    function drawDimensions() {
      uiLayer.destroyChildren();
      if (!selectedCabinet) { uiLayer.draw(); return; }
      const box = selectedCabinet.getClientRect();
      const info = selectedCabinet.userData;

      uiLayer.add(new Konva.Text({
        x: box.x, y: box.y - 15, text: `${info.width} מ"מ`, fontSize: 12, fill: '#d32f2f', fontStyle: 'bold'
      }));
      uiLayer.draw();
    }

    function updateBOM() {
      const tbody = document.getElementById('bom-body');
      const summary = document.getElementById('bom-summary');
      if (allCabinets.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: #888;">אין ארונות בשרטוט</td></tr>';
        summary.innerHTML = '';
        return;
      }
      let html = '', totalArea = 0, totalLen = 0;
      allCabinets.forEach(cab => {
        const info = cab.userData;
        const area = ((info.width * info.depth * 2) + (info.width * 720 * 2) + (info.depth * 720 * 2)) / 1000000;
        totalArea += area; totalLen += info.width;
        html += `<tr><td>${info.name}</td><td>${info.width}</td><td>${info.depth}</td><td>${area.toFixed(2)} מ"ר</td></tr>`;
      });
      tbody.innerHTML = html;
      summary.innerHTML = `סה"כ ארונות: ${allCabinets.length} | אורך: ${(totalLen/1000).toFixed(2)} מ' | שטח: ${totalArea.toFixed(2)} מ"ר`;
    }

    function deleteSelectedCabinet() {
      if (!selectedCabinet) return;
      const index = allCabinets.indexOf(selectedCabinet);
      if (index > -1) allCabinets.splice(index, 1);
      selectedCabinet.destroy();
      selectedCabinet = null;
      mainLayer.draw(); drawDimensions(); updateInspectorUI(); updateBOM(); update3DView();
    }

    function updateCabinetDimensions() {
      if (!selectedCabinet) return;
      const w = parseFloat(document.getElementById('inp-width').value) || 100;
      const d = parseFloat(document.getElementById('inp-depth').value) || 100;
      selectedCabinet.userData.width = w; selectedCabinet.userData.depth = d;

      const rect = selectedCabinet.findOne('Rect');
      const text = selectedCabinet.findOne('Text');
      rect.width(w * SCALE); rect.height(d * SCALE);
      text.width(w * SCALE); text.y((d * SCALE) / 2 - 12);
      text.text(`${selectedCabinet.userData.name}\n${w}x${d}`);
      selectedCabinet.offsetX((w * SCALE) / 2); selectedCabinet.offsetY((d * SCALE) / 2);

      mainLayer.draw(); drawDimensions(); updateBOM(); update3DView();
    }

    function updateInspectorUI() {
      const panel = document.getElementById('inspector-content');
      if (!selectedCabinet) { panel.innerHTML = '<p style="color: #888;">לחץ על ארון בשרטוט.</p>'; return; }
      const info = selectedCabinet.userData;
      panel.innerHTML = `
        <div class="prop-group"><label>שם:</label><input type="text" id="inp-name" value="${info.name}" oninput="updateCabinetName()"></div>
        <div class="prop-group"><label>רוחב (מ"מ):</label><input type="number" id="inp-width" value="${info.width}" step="50" oninput="updateCabinetDimensions()"></div>
        <div class="prop-group"><label>עומק (מ"מ):</label><input type="number" id="inp-depth" value="${info.depth}" step="50" oninput="updateCabinetDimensions()"></div>
        <button class="btn btn-delete" onclick="deleteSelectedCabinet()">🗑️ מחק ארון</button>
      `;
    }

    function updateCabinetName() {
      if (!selectedCabinet) return;
      selectedCabinet.userData.name = document.getElementById('inp-name').value;
      const text = selectedCabinet.findOne('Text');
      text.text(`${selectedCabinet.userData.name}\n${selectedCabinet.userData.width}x${selectedCabinet.userData.depth}`);
      mainLayer.draw(); updateBOM();
    }

    function selectCabinet(group) {
      if (selectedCabinet && selectedCabinet !== group) {
        selectedCabinet.findOne('Rect').stroke(selectedCabinet.userData.strokeColor).strokeWidth(2);
      }
      selectedCabinet = group;
      group.findOne('Rect').stroke('#ffaa00').strokeWidth(4);
      mainLayer.draw(); drawDimensions(); updateInspectorUI();
    }

    stage.on('click tap', (e) => {
      if (e.target === stage || e.target.parent === gridLayer) {
        if (selectedCabinet) {
          selectedCabinet.findOne('Rect').stroke(selectedCabinet.userData.strokeColor).strokeWidth(2);
          selectedCabinet = null;
          mainLayer.draw(); drawDimensions(); updateInspectorUI();
        }
      }
    });

    function addCabinet(widthMm, depthMm, name, fillColor, strokeColor, customX, customY) {
      const width = widthMm * SCALE, depth = depthMm * SCALE;
      const group = new Konva.Group({
        x: customX !== undefined ? customX : stageWidth / 2,
        y: customY !== undefined ? customY : stageHeight / 2,
        draggable: true, offsetX: width / 2, offsetY: depth / 2,
      });

      group.userData = { width: widthMm, depth: depthMm, name, fillColor, strokeColor };
      group.add(new Konva.Rect({ width: width, height: depth, fill: fillColor, stroke: strokeColor, strokeWidth: 2, cornerRadius: 2 }));
      group.add(new Konva.Text({ text: `${name}\n${widthMm}x${depthMm}`, fontSize: 12, fill: '#333', align: 'center', width: width, y: depth / 2 - 12 }));

      group.on('click tap', (e) => { e.cancelBubble = true; selectCabinet(group); });
      group.on('dragmove', () => { handleSnap(group); drawDimensions(); mainLayer.batchDraw(); update3DView(); });

      allCabinets.push(group); mainLayer.add(group); selectCabinet(group); updateBOM(); update3DView();
    }

    function exportImage() {
      const dataURL = stage.toDataURL({ pixelRatio: 2 });
      const link = document.createElement('a');
      link.download = 'kitchen-plan.png';
      link.href = dataURL;
      link.click();
    }

    function saveProject() {
      const data = allCabinets.map(cab => ({ x: cab.x(), y: cab.y(), width: cab.userData.width, depth: cab.userData.depth, name: cab.userData.name, fillColor: cab.userData.fillColor, strokeColor: cab.userData.strokeColor }));
      const a = document.createElement('a');
      a.href = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }));
      a.download = 'kitchen_design.json';
      a.click();
    }

    function loadProject(event) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = JSON.parse(e.target.result);
        allCabinets.forEach(cab => cab.destroy());
        allCabinets = []; selectedCabinet = null;
        data.forEach(item => addCabinet(item.width, item.depth, item.name, item.fillColor, item.strokeColor, item.x, item.y));
      };
      reader.readAsText(event.target.files[0]);
    }
  </script>
</body>
</html>
