import { useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { Link, Route, Routes, useLocation, useParams } from 'react-router';
import { EventCard, Filters } from './components';
import { filterEvents } from './domain';
import type { CategoryFilter, CommunityEvent } from './domain';
import { PracticeForm } from './PracticeForm';

type ExplorerProps = {
  events: CommunityEvent[]; savedIds: string[];
  onToggle: (id: string) => void; onClear?: () => void; practice?: boolean;
};
function ScreenTitle({ children }: { children: string }) {
  const ref = useRef<HTMLHeadingElement>(null);
  const location = useLocation();
  useEffect(() => {
    document.title = `${children} | Harbor Together`;
    ref.current?.focus();
  }, [children, location.key]);
  return <h1 id="screen-title" ref={ref} tabIndex={-1}>{children}</h1>;
}
function Layout({ children }: { children: ReactNode }) {
  return <><a className="skip" href="#content" onClick={event => {
      // HashRouter owns the URL fragment. Move focus without changing its route.
      event.preventDefault();
      document.getElementById('content')?.focus();
    }}>Skip to content</a>
    <header><p className="eyebrow">Harbor Together · fictional practice project</p>
      <nav aria-label="Main"><Link to="/">Explore events</Link> · <Link to="/saved">Saved events</Link></nav></header>
    <main id="content" tabIndex={-1}>{children}</main>
    <footer>Practice only. No actual registration or personal data storage.</footer></>;
}
function Explore({ events, savedIds, onToggle, onClear, onlySaved = false }: ExplorerProps & { onlySaved?: boolean }) {
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState<CategoryFilter>('all');
  const pool = onlySaved ? events.filter(event => savedIds.includes(event.id)) : events;
  const visible = filterEvents(pool, query, category);
  return <><ScreenTitle>{onlySaved ? 'Saved events' : 'Explore events'}</ScreenTitle>
    <Filters query={query} category={category} onQuery={setQuery} onCategory={setCategory} />
    {onlySaved && onClear && <button type="button" onClick={() => {
      onClear();
      document.getElementById('screen-title')?.focus();
    }}>Clear saved events</button>}
    <p role="status">{visible.length} {visible.length === 1 ? 'event' : 'events'} shown</p>
    {visible.length === 0 && <p>No events here. Change the filters or save an event from Explore.</p>}
    <div className="event-grid">{visible.map(event => <EventCard key={event.id} event={event}
      saved={savedIds.includes(event.id)} onToggle={id => {
        onToggle(id);
        // This screen removes an unsaved card. Move focus to a stable heading
        // before the active button disappears; the live result count updates next.
        if (onlySaved) document.getElementById('screen-title')?.focus();
      }}
      detailLink={<Link className="detail-link" to={`/events/${event.id}`}>View {event.title}</Link>} />)}</div>
  </>;
}
function Detail({ events, savedIds, onToggle, practice }: ExplorerProps) {
  const { eventId } = useParams();
  const event = events.find(item => item.id === eventId);
  if (!event) return <><ScreenTitle>Event not found</ScreenTitle><p>This event ID is not in the fixture.</p><Link to="/">Return to Explore</Link></>;
  return <><ScreenTitle>{event.title}</ScreenTitle>
    <EventCard event={event} saved={savedIds.includes(event.id)} onToggle={onToggle} />
    {practice && <PracticeForm key={event.id} eventTitle={event.title} />}
    <p><Link to="/">Back to all events</Link></p></>;
}
export function ExplorerRoutes(props: ExplorerProps) {
  return <Layout><Routes>
    <Route path="/" element={<Explore key="all" {...props} />} />
    <Route path="/saved" element={<Explore key="saved" {...props} onlySaved />} />
    <Route path="/events/:eventId" element={<Detail {...props} />} />
    <Route path="*" element={<><ScreenTitle>Page not found</ScreenTitle><Link to="/">Return to Explore</Link></>} />
  </Routes></Layout>;
}
