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

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

const pillInput = {
  height: BAR_H,
  background: 'var(--bg-input)',
  border: '1px solid var(--border)',
  borderRadius: 999,
  color: 'var(--text-primary)',
  fontSize: 11, fontFamily: 'var(--font)',
  padding: '0 10px',
  outline: 'none',
  boxSizing: 'border-box',
}

function Field({ label, hint, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 3, padding: '6px 0' }}>
      <span style={{ fontSize: 10, color: 'var(--text-secondary)',
                     fontWeight: 500, letterSpacing: 0.2 }}>
        {label}
      </span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>{children}</div>
      {hint && (
        <span style={{ fontSize: 9, color: 'var(--text-muted)', lineHeight: 1.4 }}>{hint}</span>
      )}
    </div>
  )
}

function SectionLabel({ children }) {
  return (
    <div style={{
      fontSize: 9, color: 'var(--text-muted)', fontWeight: 600,
      letterSpacing: 0.5, textTransform: 'uppercase',
      padding: '10px 0 4px',
      borderTop: '1px solid var(--border-light)',
      marginTop: 8,
    }}>{children}</div>
  )
}

export default function AusschnittSettingsApp() {
  const initial = (typeof window !== 'undefined' && window.PANEL_PARAMS) || {}
  const [snap, setSnap]                       = useState(initial.snap || {})
  const [displayModes, setDisplayModes]       = useState(initial.displayModes || [])
  const [overridesPresets, setOverridesPresets] = useState(initial.overridesPresets || [])
  const [layerKombis, setLayerKombis]         = useState(initial.layerKombis || [])

  useEffect(() => {
    onMessage('AUSSCHNITT_SETTINGS_STATE', (p) => {
      if (p.snap) setSnap(p.snap)
      if (Array.isArray(p.displayModes))     setDisplayModes(p.displayModes)
      if (Array.isArray(p.overridesPresets)) setOverridesPresets(p.overridesPresets)
      if (Array.isArray(p.layerKombis))      setLayerKombis(p.layerKombis)
    })
    notifyReady()
    const blockContext = (ev) => ev.preventDefault()
    document.addEventListener('contextmenu', blockContext)
    return () => document.removeEventListener('contextmenu', blockContext)
  }, [])

  const set = (patch) => setSnap(s => ({ ...s, ...patch }))

  const saveAndClose = () => {
    send('SAVE', {
      settings: {
        scale:             snap.scale || '',
        displayMode:       snap.displayMode || null,
        displayModeName:   snap.displayModeName || null,
        applyOverrides:    !!snap.applyOverrides,
        overridesEnabled:  !!snap.overridesEnabled,
        overridesPreset:   snap.overridesPreset || '',
        layerCombination:  snap.layerCombination || '',
        darstellung:       snap.darstellung || '',
      },
    })
  }

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'var(--bg-dialog)',
      display: 'flex', flexDirection: 'column',
      fontFamily: 'var(--font)', color: 'var(--text-primary)',
      overflow: 'hidden',
    }}>
      {/* Body */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 14px' }}>
        <Field label="MASSSTAB" hint="z.B. 1:50 — leer für unverändert">
          <input
            value={snap.scale || ''}
            onChange={(ev) => set({ scale: ev.target.value })}
            placeholder="1:50"
            style={{ ...pillInput, flex: 1, fontFamily: 'var(--font-mono)', minWidth: 0 }}
          />
        </Field>

        <Field label="DARSTELLUNG"
               hint="SIA-400 Detaillierungsgrad fuer diesen Ausschnitt — leer = beim Restore nicht aendern">
          <BarCombo stretch
            value={snap.darstellung || ''}
            onChange={(v) => set({ darstellung: v })}>
            <option value="">— nicht aendern —</option>
            <option value="einfach">Einfach (1:100)</option>
            <option value="standard">Standard (1:50)</option>
            <option value="detail">Detail (1:20)</option>
          </BarCombo>
        </Field>

        <Field label="BILDSCHIRMMODUS"
               hint="Display-Mode des Viewports beim Wiederherstellen">
          <BarCombo stretch
            value={snap.displayMode || ''}
            onChange={(v) => {
              const dm = displayModes.find(d => d.id === v)
              set({
                displayMode:     v || null,
                displayModeName: dm ? dm.name : null,
              })
            }}>
            <option value="">— unverändert —</option>
            {displayModes.map(dm => (
              <option key={dm.id} value={dm.id}>{dm.name}</option>
            ))}
          </BarCombo>
        </Field>

        <SectionLabel>Grafische Overrides</SectionLabel>

        <Field label="OVERRIDES BEIM RESTORE">
          <input
            type="checkbox"
            checked={!!snap.applyOverrides}
            onChange={(ev) => set({ applyOverrides: ev.target.checked })}
            style={{ marginRight: 6 }}
          />
          <span style={{ fontSize: 10, color: 'var(--text-muted)', flex: 1 }}>
            {snap.applyOverrides
              ? 'Overrides werden gesetzt'
              : 'Aktueller Overrides-Zustand bleibt'}
          </span>
        </Field>

        {snap.applyOverrides && (
          <>
            <Field label="OVERRIDES STATUS">
              <BarToggle label="AN"
                active={!!snap.overridesEnabled}
                onClick={() => set({ overridesEnabled: true })} />
              <BarToggle label="AUS"
                active={!snap.overridesEnabled}
                onClick={() => set({ overridesEnabled: false })} />
            </Field>

            <Field label="OVERRIDES PRESET"
                   hint="Leer = kein Preset (Doc-Rules bleiben)">
              <BarCombo stretch
                value={snap.overridesPreset || ''}
                onChange={(v) => set({ overridesPreset: v })}
                disabled={!snap.overridesEnabled}>
                <option value="">— kein Preset —</option>
                {overridesPresets.map(name => (
                  <option key={name} value={name}>{name}</option>
                ))}
              </BarCombo>
            </Field>
          </>
        )}

        <SectionLabel>Ebenenkombination</SectionLabel>

        <Field label="KOMBI"
               hint='"Eigene" = die per Snap gespeicherte Sichtbarkeit. Ein Preset überschreibt diese beim Wiederherstellen.'>
          <BarCombo stretch
            value={snap.layerCombination || ''}
            onChange={(v) => set({ layerCombination: v })}>
            <option value="">— Eigene Sichtbarkeit —</option>
            {layerKombis.map(name => (
              <option key={name} value={name}>{name}</option>
            ))}
          </BarCombo>
        </Field>
      </div>

      {/* Footer */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        padding: '8px 12px',
        borderTop: '1px solid var(--border)',
        background: 'var(--bg-section)',
      }}>
        <div style={{ flex: 1 }} />
        <BarToggle label="Abbrechen" onClick={() => send('CANCEL', {})} />
        <BarToggle label="Übernehmen" active onClick={saveAndClose} />
      </div>
    </div>
  )
}
