import { useEffect, useState } from 'react'
import { logError } from '../../reportError'

export interface NetworkCardController {
  mintingPot: boolean
  potHint: string | null
  clearPotHint: () => void
  mintPoToken: () => Promise<void>
  /** whether aria2c.exe shipped with this build; null while the check is in flight */
  aria2cAvailable: boolean | null
}

/**
 * View-model for the Network card's PO-token minting (L93/CC13): owns the fetch
 * state and hint copy so the card stays presentational. Also probes whether the
 * optional aria2c downloader is bundled, so the card can disable its toggle rather
 * than leave a setting that silently does nothing.
 */
export function useNetworkCard(): NetworkCardController {
  const [mintingPot, setMintingPot] = useState(false)
  const [potHint, setPotHint] = useState<string | null>(null)
  const [aria2cAvailable, setAria2cAvailable] = useState<boolean | null>(null)

  useEffect(() => {
    // Detect whether the optional aria2c downloader is bundled so the toggle can
    // disable itself instead of silently doing nothing. A failed probe leaves the
    // state null (unknown), which keeps the toggle enabled rather than wrongly
    // disabling a working feature.
    window.api.aria2cAvailable().then(setAria2cAvailable).catch(logError('aria2cAvailable'))
  }, [])

  async function mintPoToken(): Promise<void> {
    setMintingPot(true)
    setPotHint(null)
    try {
      const token = await window.api.mintPoToken()
      if (token) {
        setPotHint('Token saved.')
      } else {
        setPotHint('Token not found -- try signing into YouTube first via Cookies above.')
      }
    } catch {
      setPotHint('Failed to open YouTube window.')
    } finally {
      setMintingPot(false)
    }
  }

  return { mintingPot, potHint, clearPotHint: () => setPotHint(null), mintPoToken, aria2cAvailable }
}
