'use client';

import { useEffect, useState } from 'react';
import { checkHealth } from '@/lib/api/gateway';
import { useAuth } from '@/lib/auth';
import { Shield, LogOut } from 'lucide-react';

// NOTE: PortalHeader fetches node status + auth internally via useEffect.
// Pages that need a custom header can pass one via PortalLayout's `header` slot
// instead of modifying this component. See layout-portal.tsx PortalLayoutProps.
export default function PortalHeader() {
  const { user, logout } = useAuth();
  const [nodeStatus, setNodeStatus] = useState<'online' | 'offline' | 'checking'>('checking');
  const [nodeVersion, setNodeVersion] = useState('');

  useEffect(() => {
    let mounted = true;
    async function poll() {
      try {
        const h = await checkHealth();
        if (!mounted) return;
        setNodeStatus('online');
        setNodeVersion(h.node);
      } catch (err) {
        console.error('[PortalHeader] Health check failed:', err);
        if (!mounted) return;
        setNodeStatus('offline');
      }
    }
    poll();
    const iv = setInterval(poll, 30_000);
    return () => { mounted = false; clearInterval(iv); };
  }, []);

  return (
    <header className="sticky top-0 z-40 h-14 flex items-center justify-between px-6 glass border-b border-surface-800">
      {/* Page title slot — parent fills with children */}
      <div className="flex items-center gap-3" />

      {/* Right side */}
      <div className="flex items-center gap-4">
        {/* Node status */}
        <div className="flex items-center gap-2 text-xs">
          <span
            className={`status-dot status-dot--${nodeStatus === 'online' ? 'online' : 'offline'}`}
          />
          <span className="text-surface-400">
            {nodeStatus === 'online' ? `Node ${nodeVersion}` : 'Offline'}
          </span>
        </div>

        {/* Wallet badge */}
        {user && (
          <div className="flex items-center gap-2 pl-3 pr-2 py-1.5 rounded-lg bg-surface-800/50 text-xs">
            <Shield className="w-3.5 h-3.5 text-accent-cyan" />
            <span className="text-surface-300 font-mono">
              {user.address.slice(0, 6)}...{user.address.slice(-4)}
            </span>
            <button
              onClick={logout}
              className="ml-1 p-1 rounded-md hover:bg-surface-700 text-surface-500 hover:text-accent-rose transition-colors"
              title="Uitloggen"
            >
              <LogOut className="w-3 h-3" />
            </button>
          </div>
        )}
      </div>
    </header>
  );
}
