// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Karim Gabriele Varano
import { useState, useEffect } from 'react'
import AusschnittLayerDialog from './components/ViewportLayerDialog'
import { onMessage, notifyReady } from './lib/rhinoBridge'

function send(type, payload) {
  if (!window.RHINO_MODE) { console.log('[LayerCombinations] →', type, payload); return }
  document.title = 'RHINOMSG::' + JSON.stringify({ type, payload: payload || {} })
}

export default function LayerCombinationsApp() {
  const [layers,  setLayers]  = useState([])
  const [presets, setPresets] = useState([])

  useEffect(() => {
    onMessage('LAYER_COMBINATIONS_STATE', ({ layers: ls, presets: ps }) => {
      if (Array.isArray(ls)) setLayers(ls)
      if (Array.isArray(ps)) setPresets(ps)
    })
    notifyReady()
  }, [])

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'var(--bg-base)',
      display: 'flex',
      fontFamily: 'var(--font)',
      color: 'var(--text-primary)',
    }}>
      <AusschnittLayerDialog
        embedded
        snapName="Ebenenkombinationen"
        layers={layers}
        presets={presets}
        onClose={() => send('CANCEL')}
        onSave={(draft) => send('APPLY_COMBINATION', {
          layers: draft.map(l => ({ id: l.id, visible: l.visible, locked: l.locked })),
        })}
        onSavePreset={(name, layerStates) => send('SAVE_PRESET', { name, layers: layerStates })}
        onDeletePreset={(name) => send('DELETE_PRESET', { name })}
      />
    </div>
  )
}
