import { h } from 'preact';
import { useState, useEffect } from 'preact/hooks';
import { wsClient } from './lib/ws';
import { parseInterface } from './lib/xml';
import type { Interface } from './lib/types';
import Canvas from './Canvas';

interface Props {
  interfaceId: string;
}

export default function FullscreenMode({ interfaceId }: Props) {
  const [iface, setIface] = useState<Interface | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    wsClient.connect('/ws');
    fetch(`/api/v1/interfaces/${encodeURIComponent(interfaceId)}`)
      .then(r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.text();
      })
      .then(xml => setIface(parseInterface(xml)))
      .catch(err => setError(err instanceof Error ? err.message : String(err)));
  }, [interfaceId]);

  if (error) {
    return (
      <div class="fs-error">
        <p>Failed to load interface: {error}</p>
      </div>
    );
  }

  return (
    <div class="fs-view">
      <Canvas iface={iface} onNavigate={async (id) => {
        try {
          const res = await fetch(`/api/v1/interfaces/${encodeURIComponent(id)}`);
          if (!res.ok) throw new Error(`HTTP ${res.status}`);
          setIface(parseInterface(await res.text()));
        } catch { /* ignore */ }
      }} timeRange={null} />
    </div>
  );
}
