package tcelllivepage

// ScreenMux is a tcell screen which multiplexes a single core simulation
// screen to multiple UIs. An app draws into the core, which is projected to all
// attached screens (a PTY, SSH sessions, a browser, ...). Events from all UIs
// are forwarded into a single queue.
//
// The core is resized to the smallest attached UI, so all UIs share the same
// grid. With no UIs attached, the core keeps its default size.
//
// Projection runs in a per-UI goroutine, so a slow or dead UI never blocks the
// app's draw loop.

import (
	
	
	
	

	
)

// AttachOpts configures a single UI projection of a [ScreenMux].
type AttachOpts struct {
	// DetachOnCtrlQ detaches only this UI on Ctrl+Q instead of forwarding the
	// event to the app.
	DetachOnCtrlQ bool
	// DeferredSize excludes the UI from size negotiation until it reports its
	// first resize. Used for browsers, before a client connects.
	DeferredSize bool
	// Clients reports the number of connected clients of this UI, if any.
	// A deferred UI with no clients is kept at the core size.
	Clients func() int
}

// muxCell is a single projected cell, snapshotted at Show time.
type muxCell struct {
	x, y  int
	mainc rune
	combc []rune
	style tcell.Style
}

// MuxClient is a single UI projection of the core screen.
type MuxClient struct {
	screen tcell.Screen
	close  func()
	opts   AttachOpts
	// pending holds cells to project on the next kick, latest wins.
	pending map[int]muxCell
	// marginW, marginH are the core dims as of the last margin clear.
	marginW, marginH int
	// resync makes the next projection render even without clients.
	resync bool
	kick   chan struct{}
	done   chan struct{}
	// projectDone is closed when the projector goroutine exits.
	projectDone chan struct{}
	doneOne     sync.Once
}

// Done is closed when the UI gets detached.
func ( *MuxClient) () <-chan struct{} {
	return .done
}

// ScreenMux multiplexes one core simulation screen to multiple UIs. It
// implements [tcell.Screen] and can be passed to cview's
// Application.SetScreen.
type ScreenMux struct {
	tcell.SimulationScreen

	ctx    context.Context
	cancel context.CancelFunc

	mu      sync.Mutex
	clients []*MuxClient
	// dirty is a bitset of cells changed since the last Show.
	dirty []uint64
	w, h  int

	// UI state, replayed to new clients
	style tcell.Style
	mouse bool
	paste bool

	events   chan tcell.Event
	finiOnce sync.Once
}

var _ tcell.Screen = (*ScreenMux)(nil)

// NewScreenMux creates an initialized multiplexer with a [DefaultCols] x
// [DefaultRows] core screen. It lives as long as ctx.
func ( context.Context) (*ScreenMux, error) {
	 := tcell.NewSimulationScreen("UTF-8")
	if  := .Init();  != nil {
		return nil, 
	}
	.SetSize(DefaultCols, DefaultRows)
	.Clear()
	.Show()

	,  := context.WithCancel()
	 := &ScreenMux{
		SimulationScreen: ,
		ctx:              ,
		cancel:           ,
		events:           make(chan tcell.Event, 64),
		paste:            true,
	}
	.w, .h = .Size()
	.dirty = make([]uint64, (.w*.h+63)/64)

	return , nil
}

// Attach registers a UI screen and starts forwarding its events and cells.
func ( *ScreenMux) (
	 tcell.Screen,  func(),  AttachOpts,
) *MuxClient {
	 := &MuxClient{
		screen:      ,
		close:       ,
		opts:        ,
		pending:     make(map[int]muxCell),
		kick:        make(chan struct{}, 1),
		done:        make(chan struct{}),
		projectDone: make(chan struct{}),
	}

	.mu.Lock()
	.clients = append(.clients, )
	, ,  := .style, .mouse, .paste
	.mu.Unlock()

	.SetStyle()
	if  {
		.EnableMouse()
	}
	if  {
		.EnablePaste()
	}

	go .project()
	go .pollClient()

	// size negotiation may not change the core, but a new UI needs a full
	// redraw anyway
	.recalcSize()
	,  := .Size()
	_ = .PostEvent(tcell.NewEventResize(, ))
	// the new UI may be larger than the core
	.invalidateMargins()

	return 
}

// Detach removes a UI and releases its screen.
func ( *ScreenMux) ( *MuxClient) {
	.mu.Lock()
	 := slices.Index(.clients, )
	if  < 0 {
		.mu.Unlock()
		return
	}
	.clients = slices.Delete(.clients, , +1)
	.mu.Unlock()

	.finish()
	.recalcSize()
}

// SetDeferred excludes a UI from size negotiation and keeps its grid at the
// core size. Used when the last client of a deferred UI disconnects.
func ( *ScreenMux) ( *MuxClient,  bool) {
	.mu.Lock()
	.opts.DeferredSize = 
	 :=  && .syncDeferredLocked(, .w, .h)
	.mu.Unlock()

	.recalcSize()
	if  {
		.kick()
	}
}

// invalidateMargins makes the projector clear the area outside the core, eg
// after the core shrank or the UI grew.
func ( *ScreenMux) ( *MuxClient) {
	.mu.Lock()
	.marginW, .marginH = -1, -1
	.mu.Unlock()

	.kick()
}

// syncDeferredLocked sizes a deferred UI without clients to the core. Must be
// called with the lock held.
func ( *ScreenMux) ( *MuxClient, ,  int) bool {
	if !.opts.DeferredSize {
		return false
	}
	if .opts.Clients != nil && .opts.Clients() > 0 {
		return false
	}
	,  := .screen.(tcell.SimulationScreen)
	if ! {
		return false
	}
	if ,  := .Size();  ==  &&  ==  {
		return false
	}
	// SetSize is silent, it does not post a resize event
	.SetSize(, )
	// render the new grid even without clients
	.resync = true
	return true
}

func ( *ScreenMux) ( *MuxClient) {
	select {
	case .kick <- struct{}{}:
	default:
	}
}

func ( *MuxClient) () {
	.doneOne.Do(func() {
		close(.done)
		// Fini may block (eg on SSH), same as cview does
		go func() {
			defer func() { _ = recover() }()
			if .close != nil {
				.close()
			}
			// the projector must not write to a finalized screen
			<-.projectDone
			.screen.Fini()
		}()
	})
}

// pollClient forwards the events of a single UI until it disconnects.
func ( *ScreenMux) ( *MuxClient) {
	for {
		 := .screen.PollEvent()
		if  == nil {
			break
		}

		switch ev := .(type) {
		case *tcell.EventResize:
			if .opts.DeferredSize {
				.mu.Lock()
				.opts.DeferredSize = false
				.mu.Unlock()
			}
			// the core size is recomputed from all UIs, so drop the raw event
			.recalcSize()
			// this UI may have grown beyond the core
			.invalidateMargins()
			continue

		case *tcell.EventError:
			// eg SSH disconnect
			.Detach()
			return

		case *tcell.EventKey:
			if .opts.DetachOnCtrlQ && .Key() == tcell.KeyCtrlQ {
				.Detach()
				return
			}
		}

		if  := .post();  != nil {
			return
		}
	}

	.Detach()
}

// project writes the pending cells to a single UI.
func ( *ScreenMux) ( *MuxClient) {
	defer func() { _ = recover() }()
	defer close(.projectDone)

	for {
		select {
		case <-.kick:
		case <-.done:
			return
		}

		.mu.Lock()
		 := .pending
		.pending = make(map[int]muxCell, len())
		,  := .w, .h
		,  := .marginW, .marginH
		.marginW, .marginH = , 
		 := .resync
		// keep resync until a frame with content is projected
		if  && len() > 0 {
			.resync = false
		}
		.mu.Unlock()

		,  := .screen.Size()
		// clear the area outside the core, eg after shrinking
		 := ( !=  ||  != ) && ( <  ||  < )
		if  {
			clearClientMargins(.screen, , , , )
		}
		if len() == 0 && ! {
			if  {
				// eg a deferred screen resized with no clients, render it
				.screen.Sync()
			}
			continue
		}

		for ,  := range  {
			if .x <  && .y <  {
				.screen.SetContent(.x, .y, .mainc, .combc,
					.style)
			}
		}
		if  {
			.screen.Sync()
		} else {
			.screen.Show()
		}
	}
}

// clearClientMargins fills the part of the UI outside the core with the
// default background.
func clearClientMargins( tcell.Screen, , , ,  int) {
	for  := 0;  < ; ++ {
		 := 0
		if  <  {
			 = min(, )
		}
		for  := ;  < ; ++ {
			.SetContent(, , ' ', nil, tcell.StyleDefault)
		}
	}
}

// recalcSize resizes the core to the smallest UI and notifies the app.
func ( *ScreenMux) () {
	.mu.Lock()
	,  := 0, 0
	for ,  := range .clients {
		if .opts.DeferredSize {
			continue
		}
		,  := .screen.Size()
		if  <= 0 ||  <= 0 {
			continue
		}
		if  == 0 ||  <  {
			 = 
		}
		if  == 0 ||  <  {
			 = 
		}
	}
	if  == 0 ||  == 0 {
		,  = DefaultCols, DefaultRows
	}

	 :=  != .w ||  != .h
	var  []*MuxClient
	if  {
		.w, .h = , 
		.dirty = make([]uint64, (*+63)/64)
		for  := range .dirty {
			.dirty[] = ^uint64(0)
		}
		 = slices.Clone(.clients)
		for ,  := range  {
			.pending = make(map[int]muxCell)
			.syncDeferredLocked(, , )
		}
		.SimulationScreen.SetSize(, )
	}
	.mu.Unlock()

	if  {
		for ,  := range  {
			.kick()
		}
		_ = .PostEvent(tcell.NewEventResize(, ))
	}
}

func ( *ScreenMux) () {
	.mu.Lock()
	for  := range .dirty {
		.dirty[] = ^uint64(0)
	}
	.mu.Unlock()
}

// ///// ///// /////

// ///// TCEL SCREEN

// ///// ///// /////

// Init is a no-op, the screen is initialized by [NewScreenMux].
func ( *ScreenMux) () error {
	return nil
}

// Fini detaches all UIs and the core screen.
func ( *ScreenMux) () {
	.finiOnce.Do(func() {
		.mu.Lock()
		 := .clients
		.clients = nil
		.mu.Unlock()

		.cancel()
		for ,  := range  {
			.finish()
		}
		.SimulationScreen.Fini()
	})
}

// SetContent writes a cell to the core and marks it for projection.
func ( *ScreenMux) (
	,  int,  rune,  []rune,  tcell.Style,
) {
	.SimulationScreen.SetContent(, , , , )

	.mu.Lock()
	if  >= 0 &&  >= 0 &&  < .w &&  < .h {
		 := *.w + 
		.dirty[/64] |= 1 << uint(%64)
	}
	.mu.Unlock()
}

func ( *ScreenMux) () {
	.SimulationScreen.Clear()
	.markAll()
}

func ( *ScreenMux) ( rune,  tcell.Style) {
	.SimulationScreen.Fill(, )
	.markAll()
}

// Sync projects the current grid immediately.
func ( *ScreenMux) () {
	.markAll()
	.Show()
}

// Show snapshots the changed cells and queues them for projection. The
// snapshot is taken on the app goroutine, right after the frame has been
// drawn, so UIs never see a partially drawn frame.
func ( *ScreenMux) () {
	.SimulationScreen.Show()

	.mu.Lock()
	 := slices.Clone(.clients)
	if len() == 0 {
		.clearDirty()
		.mu.Unlock()
		return
	}

	// GetContents is safe here: SetSize also runs under m.mu
	, ,  := .SimulationScreen.GetContents()
	 := make([]muxCell, 0, 256)
	for ,  := range .dirty {
		for  != 0 {
			 := bits.TrailingZeros64()
			 &=  - 1
			 := *64 + 
			if  >= * ||  >= len() {
				continue
			}
			 := &[]
			 := muxCell{
				x:      % ,
				y:      / ,
				mainc: ' ',
				style: .Style,
			}
			if len(.Runes) > 0 {
				.mainc = .Runes[0]
				.combc = .Runes[1:]
			}
			 = append(, )
		}
	}
	.clearDirty()
	for ,  := range  {
		for ,  := range  {
			.pending[.y*+.x] = 
		}
	}
	.mu.Unlock()

	if len() == 0 {
		return
	}
	for ,  := range  {
		.kick()
	}
}

// clearDirty must be called with the lock held.
func ( *ScreenMux) () {
	for  := range .dirty {
		.dirty[] = 0
	}
}

// PollEvent returns the next event from any UI.
func ( *ScreenMux) () tcell.Event {
	select {
	case  := <-.events:
		return 
	case <-.ctx.Done():
		return nil
	}
}

// PostEvent queues an event for the app, eg an injected keystroke.
func ( *ScreenMux) ( tcell.Event) error {
	return .post()
}

func ( *ScreenMux) ( tcell.Event) error {
	select {
	case .events <- :
		return nil
	case <-.ctx.Done():
		return context.Canceled
	}
}

func ( *ScreenMux) ( tcell.Style) {
	.mu.Lock()
	.style = 
	 := slices.Clone(.clients)
	.mu.Unlock()

	.SimulationScreen.SetStyle()
	for ,  := range  {
		.screen.SetStyle()
	}
}

func ( *ScreenMux) (,  int) {
	.mu.Lock()
	 := slices.Clone(.clients)
	.mu.Unlock()

	.SimulationScreen.ShowCursor(, )
	for ,  := range  {
		.screen.ShowCursor(, )
	}
}

func ( *ScreenMux) ( ...tcell.MouseFlags) {
	.mu.Lock()
	.mouse = true
	 := slices.Clone(.clients)
	.mu.Unlock()

	.SimulationScreen.EnableMouse(...)
	for ,  := range  {
		.screen.EnableMouse(...)
	}
}

func ( *ScreenMux) () {
	.mu.Lock()
	.mouse = false
	 := slices.Clone(.clients)
	.mu.Unlock()

	.SimulationScreen.DisableMouse()
	for ,  := range  {
		.screen.DisableMouse()
	}
}

func ( *ScreenMux) () {
	.mu.Lock()
	.paste = true
	 := slices.Clone(.clients)
	.mu.Unlock()

	.SimulationScreen.EnablePaste()
	for ,  := range  {
		.screen.EnablePaste()
	}
}

func ( *ScreenMux) () {
	.mu.Lock()
	.paste = false
	 := slices.Clone(.clients)
	.mu.Unlock()

	.SimulationScreen.DisablePaste()
	for ,  := range  {
		.screen.DisablePaste()
	}
}