/* global */
// Built-in dashboard layout presets. Each preset is a full snapshot of the
// dashboard state (`order`, `hidden`, `spans`, optional `heights` and
// `widgetConfig`) that can be applied with one click. Custom user presets
// live alongside in localStorage under `pm_dash_presets`. The dashboard's
// `window.__dash_setLayout` applies a snapshot atomically.
//
// Spans are designed for the 12-column desktop grid; the masonry packer
// fills rows by natural tile height, so presets leave `heights` empty
// (natural) unless a tile really needs a fixed size. The first preset is
// also the dashboard default (DEFAULT_ORDER / DEFAULT_SPANS in dashboard.jsx).

const PRESETS_STORAGE_KEY = 'pm_dash_presets';

// Every widget id, so each preset can list what it hides explicitly.
const ALL_WIDGETS = ['station', 'tempChart', 'sensors', 'wind', 'windRose', 'barometer', 'sun', 'hourly',
  'chart', 'daily', 'extremes', 'compare', 'models', 'webcam', 'indoor', 'radar'];
const hiddenExcept = (order) => ALL_WIDGETS.filter((id) => !order.includes(id));

// rows: [[id, span, height?], …] in display order. Tiles that share a row get
// the same `height` so rows end evenly (heights act as a minimum — content
// may still grow, charts stretch to fill). Rows without a height stay natural.
function preset(id, name, icon, desc, rows) {
  const order = rows.map(([w]) => w);
  const spans = Object.fromEntries(rows.map(([w, s]) => [w, s]));
  const heights = Object.fromEntries(rows.filter((r) => r[2]).map(([w, , h]) => [w, h]));
  const rowSpans = Object.fromEntries(rows.filter((r) => r[3] > 1).map(([w, , , n]) => [w, n]));
  return {
    id, name, icon, desc,
    layout: { order: [...order, ...hiddenExcept(order)], hidden: hiddenExcept(order), spans, heights, rows: rowSpans },
  };
}

window.WIDGET_PRESETS_BUILTIN = [
  // Výchozí = Lukášova předvolba „Moje rozložení“ z exportu 22. 10. 2026 10:43
  // (release1.json, pm_dash_presets = pm_dash_layout_v4) — celý snímek, výšky
  // přirozené; jmenuje se Přehled všude (lišta, panel Vzhled, paleta). `short` =
  // kratší název do lišty, je-li třeba.
  { id: 'prehled', name: 'Přehled', icon: 'grid-1x2',
    desc: 'Výchozí: stanice, radar, webkamera, předpověď po hodinách a dnech, grafy, modely a soulad s předpovědí.',
    layout: {
      order: ["station", "radar", "webcam", "hourly", "daily", "sensors", "tempChart", "wind", "indoor", "chart", "models", "compare", "windRose", "barometer", "sun", "extremes"],
      hidden: ["windRose", "barometer", "extremes", "sensors", "wind", "indoor", "sun"],
      spans: {"station": 4, "tempChart": 8, "wind": 3, "sensors": 8, "windRose": 3, "barometer": 3, "compare": 3, "sun": 4, "hourly": 12, "chart": 5, "daily": 4, "extremes": 12, "webcam": 4, "indoor": 8, "radar": 4, "models": 4},
      heights: {},
      rows: {},
      widgetConfig: {"tempChart": {"showIcons": true, "showStats": true}, "station": {"showCompare": false}, "wind": {"showCompass": true, "showCompare": true}, "webcam": {"showCaption": true}, "radar": {"showLegend": false}},
    } },
  // Názvy Meteostanice / Statistiky schválně stejné jako v přepínači stránek (Lukáš 21. 10. 2026).
  // glyph = naše kresba meteostanice z přepínače (PresetIcon v app.jsx); icon zůstává pro paletu příkazů.
  { glyph: 'stanice', ...preset('stanice', 'Meteostanice', 'broadcast-pin', 'Jako stránka meteostanice: živá data, přístroje a extrémy.', [
    ['station', 3, 320], ['tempChart', 6, 320], ['wind', 3, 320],
    ['windRose', 4, 300], ['barometer', 4, 300], ['sun', 4, 300],
    ['sensors', 12],
    ['extremes', 12],
    ['webcam', 6], ['indoor', 6],
  ]) },
  preset('data', 'Statistiky', 'graph-up', 'Všechno: grafy, modely, přístroje, senzory i extrémy.', [
    ['station', 3, 320], ['tempChart', 6, 320], ['wind', 3, 320],
    ['chart', 12],
    ['sensors', 12],
    ['windRose', 3, 300], ['barometer', 3, 300], ['compare', 3, 300], ['models', 3, 300],
    ['hourly', 12],
    ['daily', 8, 300], ['sun', 4, 300],
    ['extremes', 12],
    ['indoor', 8], ['webcam', 4],
  ]),
];

// Výchozí rozložení lokality jen s předpovědí (stanice neposílá data, pm_bez_dat) = Lukášovo
// rozložení z exportu bez_MS.json 22. 10. 2026 13:47 (pm_dash_layout_v4 nastavené na Stodůlkách).
// Dlaždice jen se stanicí (JEN_SE_STANICI v dashboard.jsx) se bez stanice stejně neukazují.
// Ukládá se zvlášť (pm_dash_layout_bez_v1), úpravy bez stanice nemění rozložení se stanicí.
window.WIDGET_LAYOUT_BEZ_STANICE = {
  order: ["station", "radar", "webcam", "daily", "hourly", "sensors", "tempChart", "wind", "indoor", "chart", "models", "compare", "windRose", "barometer", "sun", "extremes"],
  hidden: ["windRose", "barometer", "extremes", "sensors", "wind", "indoor", "sun", "tempChart", "models"],
  spans: {"station": 4, "tempChart": 8, "wind": 3, "sensors": 8, "windRose": 3, "barometer": 3, "compare": 8, "sun": 4, "hourly": 12, "chart": 9, "daily": 3, "extremes": 12, "webcam": 3, "indoor": 8, "radar": 5, "models": 4},
  heights: {},
  rows: {"daily": 2, "radar": 4, "station": 2},
  widgetConfig: {"tempChart": {"showIcons": true, "showStats": true}, "station": {"showCompare": false}, "wind": {"showCompass": true, "showCompare": true}, "webcam": {"showCaption": true}, "radar": {"showLegend": false}},
};

// Load custom presets saved by the user. Each item must have the same shape
// as a built-in: { id, name, icon, layout }. `builtin: false` marks them
// so the UI can show delete affordances only on custom ones.
window.loadCustomPresets = function loadCustomPresets() {
  try {
    const raw = localStorage.getItem(PRESETS_STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : [];
  } catch { return []; }
};

// Every change to the preset list or its visibility fires `presets-change`
// so the on-page PresetBar and the Vzhled panel re-render.
const presetsChanged = () => window.dispatchEvent(new CustomEvent('presets-change'));

window.saveCustomPresets = function saveCustomPresets(presets) {
  try { localStorage.setItem(PRESETS_STORAGE_KEY, JSON.stringify(presets)); } catch {}
  presetsChanged();
};

// Presets hidden from the on-page bar (ids, built-in or custom) — managed in
// the Vzhled panel, stored under `pm_dash_presets_hidden`.
const PRESETS_HIDDEN_KEY = 'pm_dash_presets_hidden';
window.loadHiddenPresets = function loadHiddenPresets() {
  try {
    const v = JSON.parse(localStorage.getItem(PRESETS_HIDDEN_KEY) || '[]');
    return Array.isArray(v) ? v : [];
  } catch { return []; }
};
window.setPresetHidden = function setPresetHidden(id, hidden) {
  const s = new Set(window.loadHiddenPresets());
  if (hidden) s.add(id); else s.delete(id);
  try { localStorage.setItem(PRESETS_HIDDEN_KEY, JSON.stringify([...s])); } catch {}
  presetsChanged();
};

window.renameCustomPreset = function renameCustomPreset(id, name) {
  window.saveCustomPresets(window.loadCustomPresets().map(p => p.id === id ? { ...p, name } : p));
};

// Combined list: built-ins first, custom user presets after.
window.getAllPresets = function getAllPresets() {
  const built = (window.WIDGET_PRESETS_BUILTIN || []).map(p => ({ ...p, builtin: true }));
  const custom = window.loadCustomPresets().map(p => ({ ...p, builtin: false }));
  return [...built, ...custom];
};

// Save the current layout as a new custom preset — the whole snapshot,
// including per-widget heights and widget settings, so applying it later
// gives back exactly what the user saw. Returns the new preset id.
const snapshotLayout = (layout) => ({
  order: layout.order.slice(),
  hidden: layout.hidden.slice(),
  spans: { ...layout.spans },
  heights: { ...(layout.heights || {}) },
  rows: { ...(layout.rows || {}) },
  widgetConfig: JSON.parse(JSON.stringify(layout.widgetConfig || {})),
});

window.savePresetFromLayout = function savePresetFromLayout(name, layout) {
  const presets = window.loadCustomPresets();
  const id = 'custom-' + Date.now().toString(36);
  const preset = {
    id,
    name: name || 'Bez názvu',
    icon: 'star',
    desc: 'Vlastní preset',
    layout: snapshotLayout(layout),
  };
  window.saveCustomPresets([...presets, preset]);
  return id;
};

// Replace a custom preset's layout with the current one (keeps name and id).
window.overwriteCustomPreset = function overwriteCustomPreset(id, layout) {
  window.saveCustomPresets(window.loadCustomPresets().map(p => p.id === id ? { ...p, layout: snapshotLayout(layout) } : p));
};

window.deleteCustomPreset = function deleteCustomPreset(id) {
  const presets = window.loadCustomPresets();
  window.saveCustomPresets(presets.filter(p => p.id !== id));
};
