import { useNavigate, useLocation } from 'react-router-dom'
import { useState } from 'react'
import { useAuth } from '../contexts/AuthContext'

export default function BottomNav() {
  const navigate = useNavigate()
  const location = useLocation()
  const { user, mongoUser } = useAuth()
  const displayName = mongoUser?.displayName || user?.displayName || 'U'
  const mongoPhoto = mongoUser && 'photoURL' in mongoUser ? mongoUser.photoURL : null
  const photoURL = (mongoPhoto?.startsWith('data:')) ? mongoPhoto : (user?.photoURL || null)
  const [imgError, setImgError] = useState(false)

  const isActive = (path: string) => location.pathname === path

  return (
    <nav className="bottom-nav">
      {/* Brand – visible only in desktop sidebar */}
      <div className="bottom-nav-brand">Grateful Journal</div>

      {/* Write */}
      <button
        type="button"
        className={`bottom-nav-btn ${isActive('/write') ? 'bottom-nav-btn-active' : ''}`}
        onClick={() => navigate('/write')}
        aria-label="Write"
      >
        {/* Pencil / edit icon */}
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
          <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
          <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
        </svg>
        <span>Write</span>
      </button>

      {/* History */}
      <button
        type="button"
        id="tour-nav-history"
        className={`bottom-nav-btn ${isActive('/history') ? 'bottom-nav-btn-active' : ''}`}
        onClick={() => navigate('/history')}
        aria-label="History"
      >
        {/* Clock icon */}
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10" />
          <polyline points="12 6 12 12 16 14" />
        </svg>
        <span>History</span>
      </button>

      {/* Settings */}
      <button
        type="button"
        id="tour-nav-settings"
        className={`bottom-nav-btn ${isActive('/settings') ? 'bottom-nav-btn-active' : ''}`}
        onClick={() => navigate('/settings')}
        aria-label="Settings"
      >
        {photoURL && !imgError ? (
          <img src={photoURL} alt={displayName} className="bottom-nav-avatar" onError={() => setImgError(true)} />
        ) : (
          <div className="bottom-nav-avatar bottom-nav-avatar-placeholder">
            {displayName.charAt(0).toUpperCase()}
          </div>
        )}
        <span>Settings</span>
      </button>
    </nav>
  )
}
