import React, { useState } from 'react'
import { DataProvider, useData } from './DataContext.jsx'
import Header from './components/Header.jsx'
import TabNav from './components/TabNav.jsx'
import LoginPage, { getStoredAuth, clearStoredAuth } from './components/LoginPage.jsx'
import ElasticityResults from './tabs/ElasticityResults.jsx'
import Trends from './tabs/Trends.jsx'
import PPA from './tabs/PPA.jsx'
import Recommendations from './tabs/Recommendations.jsx'
import Simulation from './tabs/Simulation.jsx'
import BrandInteraction from './tabs/BrandInteraction.jsx'
import GrowthDecomposition from './tabs/GrowthDecomposition.jsx'
import PriceGradient from './tabs/PriceGradient.jsx'
import Methodology from './tabs/Methodology.jsx'

function Dashboard({ user, onLogout }) {
  const [activeTab, setActiveTab] = useState('results')
  const { loading, error, progress, stats } = useData()

  if (loading) {
    return (
      <div className="loading-screen">
        <h2>{stats?.brand || 'Genesis AI'}</h2>
        <p>Price Elasticity Intelligence</p>
        <div className="loading-bar-wrap">
          <div className="loading-bar" style={{ width: `${progress}%` }} />
        </div>
        <p>Loading data… {progress}%</p>
      </div>
    )
  }

  if (error) {
    return (
      <div className="loading-screen">
        <h2 style={{ color: 'var(--rd)' }}>Data Error</h2>
        <p>{error}</p>
        <p style={{ marginTop: 8 }}>Make sure the Python pipeline has run and <code>/output/</code> files exist.</p>
      </div>
    )
  }

  const tabComponents = {
    results:     <ElasticityResults />,
    trends:      <Trends />,
    ppa:         <PPA />,
    recs:        <Recommendations />,
    sim:         <Simulation />,
    interaction: <BrandInteraction />,
    growth:      <GrowthDecomposition />,
    gi:          <PriceGradient />,
    methodology: <Methodology />,
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <Header user={user} onLogout={onLogout} />
      <TabNav activeTab={activeTab} onTabChange={setActiveTab} />
      <main style={{ flex: 1 }}>
        {tabComponents[activeTab] || null}
      </main>
    </div>
  )
}

export default function App() {
  const [user, setUser] = useState(() => getStoredAuth())

  function handleLogin(u) {
    setUser(u)
  }

  function handleLogout() {
    clearStoredAuth()
    setUser(null)
  }

  if (!user) {
    return <LoginPage onLogin={handleLogin} />
  }

  return (
    <DataProvider>
      <Dashboard user={user} onLogout={handleLogout} />
    </DataProvider>
  )
}
