import React, { useState } from 'react'
import NovaSelect from '../ui/NovaSelect'

function jumpToSection(targetId) {
  if (!targetId || typeof window === 'undefined') return

  const element = document.getElementById(targetId)
  if (!element) return

  element.scrollIntoView({ behavior: 'smooth', block: 'start' })
  window.history.replaceState(null, '', `#${targetId}`)
}

export default function DocsSidebarNav({ sections, ariaLabel = 'Sections on this page', selectLabel = 'Jump to section', navTitle = 'On this page' }) {
  const [selectedSection, setSelectedSection] = useState(null)

  return (
    <>
      <div className="lg:hidden">
        <label htmlFor="groups-help-nav" className="sr-only">{selectLabel}</label>
        <NovaSelect
          id="groups-help-nav"
          className="w-full"
          value={selectedSection}
          placeholder="Jump to a section"
          options={sections.map((section) => ({ value: section.id, label: section.label }))}
          onChange={(value) => {
            jumpToSection(value)
            setSelectedSection(null)
          }}
          searchable={false}
        />
      </div>

      <nav aria-label={ariaLabel} className="hidden lg:block lg:sticky lg:top-24">
        <div className="rounded-[28px] border border-white/10 bg-white/[0.03] p-4 shadow-[0_18px_50px_rgba(2,6,23,0.22)]">
          <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80">{navTitle}</p>
          <ul className="mt-4 space-y-1.5">
            {sections.map((section) => (
              <li key={section.id}>
                <a href={`#${section.id}`} className="block rounded-2xl px-3 py-2 text-sm text-slate-300 transition hover:bg-white/[0.05] hover:text-white">
                  {section.label}
                </a>
              </li>
            ))}
          </ul>
        </div>
      </nav>
    </>
  )
}