import * as React from 'react'
import { useEffect, useState } from 'react'
import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import stripAnsi from 'strip-ansi'
import terminalImage from 'terminal-image'
import { Box, Text } from '../../ink.js'
import { env } from '../../utils/env.js'

function resolveLogoPath(): string {
  const fromModule = join(
    dirname(fileURLToPath(import.meta.url)),
    '..',
    '..',
    '..',
    'assets',
    'rios-circle.png',
  )
  if (existsSync(fromModule)) {
    return fromModule
  }
  return join(process.cwd(), 'assets', 'rios-circle.png')
}

const LOGO_WIDTH = 14

/**
 * RiOS circular mark from bundled PNG. Uses terminal half-blocks (not Kitty/iTerm
 * inline graphics) so output stays inside Ink's layout. On Apple Terminal, truecolor
 * ANSI is stripped and the glyph is drawn with theme `clawd_body` (see theme.ts).
 */
export function RiosCircleMark() {
  const [lines, setLines] = useState<string[] | null>(null)

  useEffect(() => {
    let alive = true
    const path = resolveLogoPath()
    void terminalImage
      .file(path, {
        width: LOGO_WIDTH,
        preferNativeRender: false,
      })
      .then((raw) => {
        if (!alive) return
        const trimmed = raw.trimEnd()
        if (!trimmed) {
          setLines(null)
          return
        }
        let text = trimmed
        if (env.terminal === 'Apple_Terminal') {
          text = text
            .split('\n')
            .map((line) => stripAnsi(line))
            .join('\n')
        }
        const split = text.split('\n').filter((l) => l.length > 0)
        setLines(split.length > 0 ? split : null)
      })
      .catch(() => {
        if (alive) setLines(null)
      })
    return () => {
      alive = false
    }
  }, [])

  if (lines == null) {
    return (
      <Box flexDirection="column" height={3} justifyContent="center" alignItems="center">
        <Text color="clawd_body"> ▄▄▄▄▄▄▄▄ </Text>
        <Text color="clawd_body"> ████████ </Text>
        <Text color="clawd_body"> ▀▀▀▀▀▀▀▀ </Text>
      </Box>
    )
  }

  const themeOnly = env.terminal === 'Apple_Terminal'
  return (
    <Box flexDirection="column" alignItems="center">
      {lines.map((line, i) =>
        themeOnly ? (
          <Text key={i} color="clawd_body">
            {line}
          </Text>
        ) : (
          <Text key={i}>{line}</Text>
        ),
      )}
    </Box>
  )
}
