// frontend/src/components/layout/Header.jsx
// Fixed top bar — covers only the content area (left: --sidebar-width).
//
// Left:  hamburger (mobile) + breadcrumb trail
// Right: global search · notifications · settings · separator · profile w/ dropdown

import { useState, useEffect, useRef } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '@/hooks/useAuth'
import api from '@/lib/api'
import HeaderSearch from '@/components/ui/HeaderSearch'

// ─── Breadcrumb config ────────────────────────────────────────────────────────

const STATIC_LABELS = {
  '':                'Home',
  dashboard:         'Dashboard',
  devices:           'Devices',
  users:             'App Users',
  mqtt:              'MQTT',
  commands:          'Commands',
  logs:              'Logs',
  equipment:         'Equipment',
  notes:             'Issues & Notes',
  mail:              'Mail',
  crm:               'CRM',
  comms:             'Activity Log',
  customers:         'Customers',
  orders:            'Orders',
  products:          'Products',
  quotations:        'Quotations',
  new:               'New',
  edit:              'Edit',
  melodies:          'Melodies',
  archetypes:        'Archetypes',
  settings:          'Settings',
  composer:          'Composer',
  manufacturing:     'Manufacturing',
  batch:             'Batch',
  provision:         'Provision Device',
  firmware:          'Firmware',
  developer:         'Developer',
  api:               'API Reference',
  staff:             'Staff',
  sn:                'S/N Manager',
  'staff-log':       'Staff Log',
  'serial-logs':     'Log Viewer',
  'public-features': 'Public Features',
}

const ENTITY_RESOLVERS = {
  customers:  { path: (id) => `/crm/customers/${id}`,    label: (d) => [d.name, d.surname].filter(Boolean).join(' ') || d.organization || null },
  products:   { path: (id) => `/crm/products/${id}`,     label: (d) => d.name || null },
  quotations: { path: (id) => `/crm/quotations/${id}`,   label: (d) => d.quotation_number || null },
  devices:    { path: (id) => `/devices/${id}`,          label: (d) => d.name || d.device_id || null },
  orders:     { path: (id) => `/crm/orders/${id}`,       label: (d) => d.order_number || null },
  melodies:   { path: (id) => `/melodies/${id}`,         label: (d) => d.name || null },
  archetypes: { path: (id) => `/builder/melodies/${id}`, label: (d) => d.name || null },
  users:      { path: (id) => `/users/${id}`,            label: (d) => d.name || d.display_name || null },
  notes:      { path: (id) => `/equipment/notes/${id}`,  label: (d) => d.title || d.subject || null },
  staff:      { path: (id) => `/staff/${id}`,            label: (d) => d.name || null },
}

const labelCache = {}

async function fetchEntityLabel(type, id) {
  const key = `${type}:${id}`
  if (labelCache[key]) return labelCache[key]
  const resolver = ENTITY_RESOLVERS[type]
  if (!resolver) return id
  try {
    const data = await api.get(resolver.path(id))
    const raw = resolver.label(data)
    if (raw) {
      const label = String(raw).length > 28 ? String(raw).slice(0, 26) + '…' : String(raw)
      labelCache[key] = label
      return label
    }
  } catch {
    // fall back to raw id
  }
  return id
}

function parseSegments(pathname) {
  const parts = pathname.split('/').filter(Boolean)
  const segments = [{ label: 'Home', to: '/' }]
  let i = 0

  while (i < parts.length) {
    const part = parts[i]
    const built = '/' + parts.slice(0, i + 1).join('/')

    if (part === 'crm') {
      segments.push({ label: 'CRM', to: '/crm/customers' })
      i++; continue
    }
    if (part === 'equipment' && parts[i + 1] === 'notes') {
      segments.push({ label: 'Issues & Notes', to: '/equipment/notes' })
      i += 2; continue
    }
    if (part === 'manufacturing' && parts[i + 1] === 'provision') {
      segments.push({ label: 'Manufacturing', to: '/manufacturing' })
      segments.push({ label: 'Provision Device', to: '/manufacturing/provision' })
      i += 2; continue
    }

    const staticLabel = STATIC_LABELS[part]
    if (staticLabel) {
      segments.push({ label: staticLabel, to: built })
    } else {
      const prevPart = parts[i - 1]
      const fetchType = ENTITY_RESOLVERS[prevPart] ? prevPart : null
      segments.push({ label: part, to: built, dynamicId: part, fetchType })
    }
    i++
  }

  return segments
}

// ─── Breadcrumb ───────────────────────────────────────────────────────────────

function Breadcrumb() {
  const location = useLocation()
  const [segments, setSegments] = useState(() => parseSegments(location.pathname))

  useEffect(() => {
    const parsed = parseSegments(location.pathname)
    setSegments(parsed)

    const dynamics = parsed.filter((s) => s.fetchType && s.dynamicId)
    if (!dynamics.length) return

    let cancelled = false
    ;(async () => {
      const resolved = [...parsed]
      for (const seg of dynamics) {
        const label = await fetchEntityLabel(seg.fetchType, seg.dynamicId)
        if (cancelled) return
        const idx = resolved.findIndex(
          (s) => s.dynamicId === seg.dynamicId && s.fetchType === seg.fetchType
        )
        if (idx !== -1) resolved[idx] = { ...resolved[idx], label }
      }
      if (!cancelled) setSegments([...resolved])
    })()

    return () => { cancelled = true }
  }, [location.pathname])

  if (segments.length <= 1) return null

  const display = segments.slice(1)

  return (
    <nav aria-label="Breadcrumb" className="header-breadcrumb-nav">
      {display.map((seg, i) => (
        <span
          key={i}
          style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', minWidth: 0, flexShrink: i === display.length - 1 ? 1 : 0 }}
        >
          {i > 0 && (
            <span className="header-breadcrumb-sep" aria-hidden="true">
              <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor"
                strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"
              >
                <path d="M3 2l4 3-4 3" />
              </svg>
            </span>
          )}
          {i === display.length - 1 ? (
            <span aria-current="page" className="header-breadcrumb-current">
              {seg.label}
            </span>
          ) : (
            <Link to={seg.to} className="header-breadcrumb-link">
              {seg.label}
            </Link>
          )}
        </span>
      ))}
    </nav>
  )
}

// ─── Icons ────────────────────────────────────────────────────────────────────

function HamburgerIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none"
      stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"
      aria-hidden="true" focusable="false"
    >
      <path d="M3 5h14M3 10h14M3 15h14" />
    </svg>
  )
}

function BellIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none"
      stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"
      aria-hidden="true" focusable="false"
    >
      <path d="M8 2a4 4 0 0 1 4 4v3l1 2H3l1-2V6a4 4 0 0 1 4-4z" />
      <path d="M6.5 13.5a1.5 1.5 0 0 0 3 0" />
    </svg>
  )
}

function GearIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"
      aria-hidden="true" focusable="false"
    >
      <circle cx="12" cy="12" r="3" />
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
    </svg>
  )
}

function SignOutIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 15 15" fill="none"
      stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"
      aria-hidden="true" focusable="false"
    >
      <path d="M5.5 2.5H3A1 1 0 0 0 2 3.5v8A1 1 0 0 0 3 12.5h2.5" />
      <path d="M10 5l3 2.5L10 10" />
      <path d="M13 7.5H6" />
    </svg>
  )
}

// ─── Profile dropdown ─────────────────────────────────────────────────────────

function ProfileMenu({ onClose, onSignOut }) {
  useEffect(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose() }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [onClose])

  return (
    <div className="profile-menu" role="menu">
      <button
        type="button"
        role="menuitem"
        className="profile-menu-item profile-menu-item--danger"
        onClick={onSignOut}
      >
        <SignOutIcon />
        Sign out
      </button>
    </div>
  )
}

// ─── Settings dropdown ────────────────────────────────────────────────────────

const SETTINGS_ITEMS = [
  {
    to: '/settings/staff',
    label: 'Staff Management',
    icon: (
      <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <circle cx="8" cy="5" r="3"/>
        <path d="M2 14c0-3.31 2.69-6 6-6s6 2.69 6 6"/>
      </svg>
    ),
  },
  {
    to: '/settings/public-features',
    label: 'Public Features',
    icon: (
      <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M2 8a6 6 0 1 0 12 0A6 6 0 0 0 2 8z"/>
        <path d="M8 2a9 9 0 0 0 0 12M8 2a9 9 0 0 1 0 12M2 8h12"/>
      </svg>
    ),
  },
  {
    to: '/settings/serial-logs',
    label: 'Log Viewer',
    icon: (
      <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <rect x="2" y="2" width="12" height="12" rx="1.5"/>
        <path d="M5 6h6M5 9h4M5 12h2"/>
      </svg>
    ),
  },
  {
    to: '/settings/pages',
    label: 'Page Settings',
    placeholder: true,
    icon: (
      <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <circle cx="8" cy="8" r="2.5"/>
        <path d="M8 2v1.5M8 12.5V14M2 8h1.5M12.5 8H14M3.5 3.5l1 1M11.5 11.5l1 1M3.5 12.5l1-1M11.5 4.5l1-1"/>
      </svg>
    ),
  },
]

function SettingsMenu({ onClose }) {
  const navigate = useNavigate()

  useEffect(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose() }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [onClose])

  return (
    <div
      style={{
        position: 'absolute',
        top: 'calc(100% + 8px)',
        right: 0,
        zIndex: 9999,
        minWidth: 200,
        backgroundColor: 'var(--color-bg-float)',
        backdropFilter: 'blur(12px)',
        WebkitBackdropFilter: 'blur(12px)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-md)',
        boxShadow: 'var(--shadow-lg)',
        overflow: 'hidden',
      }}
      role="menu"
    >
      <div style={{
        padding: 'var(--space-2) var(--space-3)',
        borderBottom: '1px solid var(--color-border)',
        fontSize: 'var(--font-size-xs)',
        fontWeight: 'var(--font-weight-semibold)',
        color: 'var(--color-text-muted)',
        textTransform: 'uppercase',
        letterSpacing: 'var(--tracking-wide)',
      }}>
        Console Settings
      </div>
      {SETTINGS_ITEMS.map((item) => (
        <button
          key={item.to}
          type="button"
          role="menuitem"
          disabled={item.placeholder}
          onClick={() => {
            if (!item.placeholder) {
              navigate(item.to)
              onClose()
            }
          }}
          style={{
            width: '100%',
            display: 'flex',
            alignItems: 'center',
            gap: 'var(--space-2)',
            padding: 'var(--space-2) var(--space-3)',
            backgroundColor: 'transparent',
            border: 'none',
            cursor: item.placeholder ? 'default' : 'pointer',
            fontSize: 'var(--font-size-sm)',
            color: item.placeholder ? 'var(--color-text-muted)' : 'var(--color-text-secondary)',
            textAlign: 'left',
            opacity: item.placeholder ? 0.5 : 1,
            transition: 'background-color 0.1s',
          }}
          onMouseEnter={(e) => { if (!item.placeholder) e.currentTarget.style.backgroundColor = 'var(--color-bg-elevated)' }}
          onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent' }}
        >
          {item.icon}
          <span style={{ flex: 1 }}>{item.label}</span>
          {item.placeholder && (
            <span style={{
              fontSize: 'var(--font-size-xs)',
              fontWeight: 'var(--font-weight-semibold)',
              color: 'var(--color-text-muted)',
              backgroundColor: 'var(--color-bg-elevated)',
              borderRadius: 'var(--radius-full)',
              padding: '1px 6px',
              letterSpacing: '0.04em',
            }}>
              soon
            </span>
          )}
        </button>
      ))}
    </div>
  )
}

// ─── Header ───────────────────────────────────────────────────────────────────

export default function Header({ onMenuOpen }) {
  const { user, logout, hasRole } = useAuth()
  const [search, setSearch] = useState('')
  const [profileOpen, setProfileOpen] = useState(false)
  const [settingsOpen, setSettingsOpen] = useState(false)
  const profileRef = useRef(null)
  const settingsRef = useRef(null)
  const canManageSettings = hasRole('sysadmin', 'admin')

  useEffect(() => {
    if (!profileOpen) return
    const handler = (e) => {
      if (!profileRef.current?.contains(e.target)) setProfileOpen(false)
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [profileOpen])

  useEffect(() => {
    if (!settingsOpen) return
    const handler = (e) => {
      if (!settingsRef.current?.contains(e.target)) setSettingsOpen(false)
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [settingsOpen])

  const initials = user?.name
    ? user.name.split(' ').map((w) => w[0]).slice(0, 2).join('').toUpperCase()
    : '?'

  return (
    <header className="header">
      {/* ── Mobile hamburger ── */}
      <button
        type="button"
        onClick={onMenuOpen}
        aria-label="Open navigation menu"
        className="header-hamburger"
      >
        <HamburgerIcon />
      </button>

      {/* ── Breadcrumb ── */}
      <Breadcrumb />

      {/* ── Flex spacer ── */}
      <div className="header-spacer" />

      {/* ── Right controls ── */}
      <div className="header-right">

        <div className="header-search">
          <HeaderSearch value={search} onChange={setSearch} placeholder="Search…" />
        </div>

        <button type="button" className="header-icon-btn" aria-label="Notifications">
          <BellIcon />
        </button>

        {canManageSettings && (
          <div style={{ position: 'relative' }} ref={settingsRef}>
            <button
              type="button"
              className="header-icon-btn"
              aria-label="Console settings"
              aria-haspopup="menu"
              aria-expanded={settingsOpen}
              onClick={() => setSettingsOpen((p) => !p)}
              style={settingsOpen ? { backgroundColor: 'var(--color-bg-elevated)', color: 'var(--color-text-primary)' } : undefined}
            >
              <GearIcon />
            </button>
            {settingsOpen && (
              <SettingsMenu onClose={() => setSettingsOpen(false)} />
            )}
          </div>
        )}

        <div className="header-vsep" aria-hidden="true" />

        <div className="header-profile-wrap" ref={profileRef}>
          <button
            type="button"
            className="header-profile"
            onClick={() => setProfileOpen((p) => !p)}
            aria-expanded={profileOpen}
            aria-haspopup="menu"
            aria-label="Profile menu"
          >
            {user && (
              <div className="header-profile-info">
                <span className="header-profile-name">{user.name}</span>
                {user.role && (
                  <span className="header-profile-role">{user.role}</span>
                )}
              </div>
            )}
            <div className="header-avatar" aria-hidden="true">
              {initials}
            </div>
          </button>

          {profileOpen && (
            <ProfileMenu
              onClose={() => setProfileOpen(false)}
              onSignOut={logout}
            />
          )}
        </div>

      </div>
    </header>
  )
}
