import type { App } from '../../shared/types'
import { apps, getSelectedTab, setSelectedTab } from '../state'
import { Tab, TabBar } from '../styles'
import { resetToolIframe } from '../tool-iframes'

export function Nav({ app, render }: { app: App; render: () => void }) {
  const selectedTab = getSelectedTab(app.name)

  const handleTabClick = (tab: string) => {
    // If clicking already-selected tool tab, reset to home
    if (tab === selectedTab && tab !== 'overview') {
      resetToolIframe(tab, app.name)
      return
    }
    setSelectedTab(app.name, tab)
    render()
  }

  // Find all tools
  const tools = apps.filter(a => a.tool)
  const titlecase = (s: string) => s.split(' ').map(part => part[0]?.toUpperCase() + part.slice(1))

  return (
    <TabBar>
      <Tab active={selectedTab === 'overview' ? true : undefined} onClick={() => handleTabClick('overview')}>
        Overview
      </Tab>
      {tools.map(tool => {
        const toolName = typeof tool.tool === 'string' ? tool.tool : tool.name
        return (
          <Tab
            key={tool.name}
            active={selectedTab === tool.name ? true : undefined}
            onClick={() => handleTabClick(tool.name)}
          >
            {titlecase(toolName)}
          </Tab>
        )
      })}
    </TabBar>
  )
}
