import { useEffect, useMemo } from 'react';
import type { LayoutNode } from 'officerdev';
import { WorkspaceView } from 'officerdev';
import { useDashboardState } from 'state/useDashboardState';
import { defaultLayout } from './defaultLayout';

// /soulseek uses the Workspace/Panel system (like /chat and /music): a section nav (soulseek-nav) on
// the left and a section view (soulseek-view) on the right, coordinating via the 'soulseek:section'
// channel. Both talk to slskd through the /api/slskd auth proxy.

const ALLOWED_APP_TYPES = new Set<string | null>(['soulseek-nav', 'soulseek-view', null]);

function normalizeLayout(node: LayoutNode): LayoutNode {
  if (node.type === 'panel') {
    return ALLOWED_APP_TYPES.has(node.appType) ? node : { ...node, appType: 'soulseek-view' };
  }
  const children = node.children.map((c) => {
    const fixed = normalizeLayout(c.node);
    return fixed === c.node ? c : { ...c, node: fixed };
  });
  const changed = children.some((c, i) => c !== node.children[i]);
  return changed ? { ...node, children } : node;
}

export const SoulseekScreen = () => {
  // v2: nav + view (replaced the earlier search + transfers split) — new key so the old persisted
  // layout doesn't resurrect as two mismatched panels.
  const rawWorkspace = useDashboardState<LayoutNode>('screens/soulseek-v2', defaultLayout);

  const workspace = useMemo(() => {
    const fixed = normalizeLayout(rawWorkspace.value);
    if (fixed === rawWorkspace.value) return rawWorkspace;
    return { ...rawWorkspace, value: fixed };
  }, [rawWorkspace]);

  useEffect(() => {
    if (rawWorkspace.isLoaded && workspace.value !== rawWorkspace.value) {
      rawWorkspace.setValue(workspace.value);
    }
  }, [rawWorkspace.isLoaded, workspace.value, rawWorkspace.value]);

  return (
    <div className="h-full w-full pt-2">
      <WorkspaceView workspace={workspace} locked />
    </div>
  );
};
