import type { App } from '../../shared/types'
import { navigate } from '../router'
import { apps, getSelectedTab } 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
    }
    navigate(tab === 'overview' ? `/app/${app.name}` : `/app/${app.name}/${tab}`)
  }

  // Find tools that show on app pages (apps !== false)
  const tools = apps.filter(a => a.tool && a.apps !== false)
  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)}
          >
            {tool.icon} {titlecase(toolName)}
          </Tab>
        )
      })}
    </TabBar>
  )
}
