import { useState, useCallback } from 'react';

const STORAGE_KEY = 'screener-canvas-layout-v1';

function readPositions(initial) {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return initial;
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== 'object') return initial;
    // 누락 ID 보충
    return { ...initial, ...filterValidEntries(parsed) };
  } catch {
    return initial;
  }
}

function filterValidEntries(obj) {
  const out = {};
  for (const [k, v] of Object.entries(obj)) {
    if (v && typeof v.x === 'number' && typeof v.y === 'number') {
      out[k] = { x: v.x, y: v.y };
    }
  }
  return out;
}

export function useCanvasLayout(initialPositions) {
  const [positions, setPositions] = useState(() => readPositions(initialPositions));

  const updateNodePosition = useCallback((nodeId, pos) => {
    setPositions((prev) => {
      const next = { ...prev, [nodeId]: { x: pos.x, y: pos.y } };
      try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } catch { /* ignore quota/security errors */ }
      return next;
    });
  }, []);

  const reset = useCallback(() => {
    setPositions(initialPositions);
    try { localStorage.removeItem(STORAGE_KEY); } catch { /* ignore security errors */ }
  }, [initialPositions]);

  return { positions, updateNodePosition, reset };
}
