'use client'

import * as React from 'react'

/**
 * Lightweight hash-based router.
 *
 * The sandbox only exposes the `/` route, so we render the entire
 * multi-page pharmaceutical website inside a single Next.js page and
 * switch between "pages" using the URL hash (e.g. `#/about`).
 */

export type RouteKey =
  | 'home'
  | 'about'
  | 'research'
  | 'specialty'
  | 'vitamins'
  | 'api'
  | 'manufacturing'
  | 'quality'
  | 'biotechnology'
  | 'cdmo'
  | 'innovation'
  | 'sustainability'
  | 'knowledge'
  | 'investors'
  | 'careers'
  | 'news'
  | 'contact'
  | 'privacy'
  | 'terms'
  | 'cookies'
  | 'pharmacovigilance'

export const ROUTE_META: Record<
  RouteKey,
  { title: string; short: string; group: string; description: string }
> = {
  home: { title: 'Home', short: 'Home', group: 'Top', description: 'Espandiar Pharmaceuticals — science, precisely human.' },
  about: { title: 'About', short: 'About', group: 'Company', description: 'Corporate profile, philosophy, vision, mission, values and roadmap.' },
  research: { title: 'Research & Development', short: 'R&D', group: 'Science', description: 'Drug discovery, preclinical development, formulation, pharmacokinetics and AI-assisted research.' },
  specialty: { title: 'Specialty Medicines', short: 'Specialty', group: 'Science', description: 'Therapeutic focus across oncology, neurology, rare diseases, immunology, cardiovascular and infectious diseases.' },
  vitamins: { title: 'Advanced Vitamins', short: 'Vitamins', group: 'Science', description: 'Liposomal vitamins, clinical nutrition and advanced delivery technologies.' },
  api: { title: 'Pharmaceutical Raw Materials (API)', short: 'API', group: 'Science', description: 'Active pharmaceutical ingredients, excipients, intermediates and high-purity chemicals.' },
  manufacturing: { title: 'Manufacturing', short: 'Manufacturing', group: 'Operations', description: 'Tablet, capsule, sterile, lyophilization and packaging capabilities.' },
  quality: { title: 'Quality Assurance', short: 'Quality', group: 'Operations', description: 'GMP, GLP, GDP, ICH guidelines, validation, CAPA and data integrity.' },
  biotechnology: { title: 'Biotechnology', short: 'Biotech', group: 'Science', description: 'Monoclonal antibodies, recombinant proteins, cell and gene therapy, bioprocessing.' },
  cdmo: { title: 'CDMO Services', short: 'CDMO', group: 'Operations', description: 'Contract development and manufacturing for global pharmaceutical partners.' },
  innovation: { title: 'Innovation', short: 'Innovation', group: 'Science', description: 'AI drug discovery, nanotechnology and the future of pharmaceutical research.' },
  sustainability: { title: 'Sustainability', short: 'Sustainability', group: 'Responsibility', description: 'Green manufacturing, renewable energy, carbon reduction and ESG principles.' },
  knowledge: { title: 'Knowledge Center', short: 'Knowledge', group: 'Resources', description: 'Scientific articles, white papers, research summaries and a medical glossary.' },
  investors: { title: 'Investors', short: 'Investors', group: 'Company', description: 'Corporate governance, business strategy, ESG and long-term vision.' },
  careers: { title: 'Careers', short: 'Careers', group: 'Company', description: 'Scientific and engineering careers at a research-led pharmaceutical company.' },
  news: { title: 'News', short: 'News', group: 'Resources', description: 'Announcements, research highlights and corporate news.' },
  contact: { title: 'Contact', short: 'Contact', group: 'Top', description: 'Business development, API sales, CDMO, media, investor relations and scientific collaboration.' },
  privacy: { title: 'Privacy Policy', short: 'Privacy', group: 'Legal', description: 'Espandiar Pharmaceuticals privacy notice and data protection policy.' },
  terms: { title: 'Terms of Use', short: 'Terms', group: 'Legal', description: 'Terms and conditions governing the use of espandiar.com.' },
  cookies: { title: 'Cookie Settings', short: 'Cookies', group: 'Legal', description: 'How Espandiar Pharmaceuticals uses cookies and tracking technologies.' },
  pharmacovigilance: { title: 'Pharmacovigilance', short: 'PV', group: 'Legal', description: 'Adverse event reporting, product safety and pharmacovigilance services.' },
}

function parseHash(): RouteKey {
  if (typeof window === 'undefined') return 'home'
  const raw = window.location.hash.replace(/^#\/?/, '').split('?')[0].trim()
  if (!raw) return 'home'
  const key = raw as RouteKey
  return ROUTE_META[key] ? key : 'home'
}

interface RouterContextValue {
  route: RouteKey
  navigate: (next: RouteKey) => void
}

const RouterContext = React.createContext<RouterContextValue>({
  route: 'home',
  navigate: () => {},
})

export function RouterProvider({ children }: { children: React.ReactNode }) {
  const [route, setRoute] = React.useState<RouteKey>('home')

  React.useEffect(() => {
    setRoute(parseHash())
    const onHashChange = () => {
      setRoute(parseHash())
      // Scroll to top on every route change for a true "page" feel.
      window.scrollTo({ top: 0, behavior: 'auto' })
    }
    window.addEventListener('hashchange', onHashChange)
    window.addEventListener('popstate', onHashChange)
    return () => {
      window.removeEventListener('hashchange', onHashChange)
      window.removeEventListener('popstate', onHashChange)
    }
  }, [])

  const navigate = React.useCallback((next: RouteKey) => {
    if (typeof window === 'undefined') return
    if (next === 'home') {
      window.location.hash = ''
    } else {
      window.location.hash = `#/${next}`
    }
    setRoute(next)
    window.scrollTo({ top: 0, behavior: 'auto' })
  }, [])

  const value = React.useMemo(() => ({ route, navigate }), [route, navigate])

  return <RouterContext.Provider value={value}>{children}</RouterContext.Provider>
}

export function useRouter() {
  return React.useContext(RouterContext)
}

/** Hook that returns true when the current route matches the given key. */
export function useIsActive(key: RouteKey) {
  const { route } = useRouter()
  return route === key
}
