package csscolorparser

import (
	
	
	
	
)

type tokenKind uint8

const (
	tokEOF tokenKind = iota
	tokNum
	tokIdent
	tokAdd
	tokSub
	tokMul
	tokDiv
	tokLParen
	tokRParen
	tokUnknown
)

// token is a lexical token. Only the field matching kind is meaningful.
type token struct {
	kind  tokenKind
	num   float64 // tokNum
	ident string  // tokIdent
}

type lexer struct {
	src string
	pos int
}

func isSpace( byte) bool {
	return  == ' ' ||  == '\t' ||  == '\n' ||  == '\f' ||  == '\r'
}

func isDigit( byte) bool { return  >= '0' &&  <= '9' }

func isAlpha( byte) bool { return ( >= 'a' &&  <= 'z') }

// scan returns the next token. At end of input it returns tokEOF, and keeps
// returning it on every later call.
func ( *lexer) () token {
	for .pos < len(.src) && isSpace(.src[.pos]) {
		.pos++
	}
	if .pos >= len(.src) {
		return token{kind: tokEOF}
	}

	 := .src[.pos]
	.pos++

	switch  {
	case '+':
		return token{kind: tokAdd}
	case '-':
		return token{kind: tokSub}
	case '*':
		return token{kind: tokMul}
	case '/':
		return token{kind: tokDiv}
	case '(':
		return token{kind: tokLParen}
	case ')':
		return token{kind: tokRParen}
	}

	if isDigit() ||  == '.' {
		return .number()
	}
	if isAlpha() {
		return .ident()
	}
	return token{kind: tokUnknown}
}

// number is called after the first byte (a digit or '.') has been consumed.
func ( *lexer) ( byte) token {
	 := .pos - 1
	 :=  == '.'

	for .pos < len(.src) {
		 := .src[.pos]
		if isDigit() {
			.pos++
		} else if  == '.' && ! {
			 = true
			.pos++
		} else {
			break
		}
	}

	// A digit string too long for float64 comes back as ±Inf with ErrRange;
	// that's accepted here, and callers reject non-finite results.
	,  := strconv.ParseFloat(.src[:.pos], 64)
	if  != nil && !errors.Is(, strconv.ErrRange) {
		return token{kind: tokUnknown} // Triggered by isolated dots (e.g., ".")
	}
	return token{kind: tokNum, num: }
}

// ident is called after the first byte (an ASCII letter) has been consumed.
// Identifiers consist solely of ASCII letters: no digits, no underscores.
func ( *lexer) () token {
	 := .pos - 1
	for .pos < len(.src) && isAlpha(.src[.pos]) {
		.pos++
	}
	return token{kind: tokIdent, ident: .src[:.pos]}
}

//---

const maxDepth = 64

// prefixBP is the binding power of unary + and -, which binds tighter than
// any binary operator.
const prefixBP = 5

// VarLookup resolves a variable name. ok is false if the name is undefined.
type varLookup func(name string) (value float64, ok bool)

// Eval evaluates an arithmetic expression made of numbers, variables,
// parentheses, unary + and -, and the binary operators + - * /.
//
// Variable names consist only of ASCII letters and are resolved with vars;
// a nil vars means no variables are defined.
//
// ok is false on a syntax error, an undefined variable, nesting deeper than
// the internal limit, or trailing input after a complete expression.
// Division follows IEEE 754, so the result may be ±Inf or NaN.
func eval( string,  varLookup) ( float64,  bool) {
	 := parser{lex: lexer{src: }, vars: }
	.next()

	,  := .expr(0)
	if ! || .tok.kind != tokEOF {
		return 0, false
	}
	return , true
}

type parser struct {
	lex   lexer
	tok   token // current lookahead; kind is tokEOF at end of input
	vars  varLookup
	depth int
}

func ( *parser) () { .tok = .lex.scan() }

// infixBP returns the left and right binding powers of a binary operator.
// ok is false if kind is not a binary operator.
func infixBP( tokenKind) (,  int,  bool) {
	switch  {
	case tokAdd, tokSub:
		return 1, 2, true
	case tokMul, tokDiv:
		return 3, 4, true
	}
	return 0, 0, false
}

// expr parses and evaluates an expression whose operators all bind at least
// as tightly as minBP.
func ( *parser) ( int) (float64, bool) {
	if .depth > maxDepth {
		return 0, false
	}
	.depth++
	defer func() { .depth-- }()

	,  := .operand()
	if ! {
		return 0, false
	}

	for {
		, ,  := infixBP(.tok.kind)
		if ! ||  <  {
			// EOF, a non-operator token, or an operator that binds too
			// loosely for this level. The caller decides what's valid.
			return , true
		}

		 := .tok.kind
		.next()

		,  := .()
		if ! {
			return 0, false
		}

		switch  {
		case tokAdd:
			 += 
		case tokSub:
			 -= 
		case tokMul:
			 *= 
		case tokDiv:
			 /= 
		}
	}
}

// operand parses a number, variable, parenthesized expression, or a
// unary + / - applied to an operand.
func ( *parser) () (float64, bool) {
	switch .tok.kind {
	case tokNum:
		 := .tok.num
		.next()
		return , true

	case tokIdent:
		,  := .vars(.tok.ident)
		if ! {
			return 0, false
		}
		.next()
		return , true

	case tokAdd, tokSub:
		 := .tok.kind == tokSub
		.next()
		,  := .expr(prefixBP)
		if ! {
			return 0, false
		}
		if  {
			 = -
		}
		return , true

	case tokLParen:
		.next()
		,  := .expr(0)
		if ! || .tok.kind != tokRParen {
			return 0, false
		}
		.next()
		return , true
	}

	return 0, false
}

//---

// Variable is a named constant usable as a bare keyword or inside calc(...).
type variable struct {
	Name  string
	Value float64
}

// parseComponent parses one component, which is one of:
//
//   - "none": zero, not a percentage
//   - a finite number, or a variable name
//   - a percentage like "50%", stored as 0.5 with IsPercent set
//   - calc(expr), where expr is evaluated by Eval and must come out finite
//
// s and the variable names are expected to be lowercase; matching is exact.

// returns (t, ok, pct)
func parseComponent( string,  [4]variable) (float64, bool, bool) {
	 := func( string) (float64, bool) {
		if ,  := parseNumber();  {
			if !isFinite() {
				return 0, false
			}
			return , true
		}
		for ,  := range  {
			if  == .Name {
				return .Value, true
			}
		}
		return 0, false
	}

	// none
	if  == "none" {
		return 0, true, false
	}

	// bare number or keyword
	if ,  := ();  {
		return , true, false
	}

	// percentage
	if ,  := strings.CutSuffix(, "%");  {
		,  := parseNumber()
		if ! || !isFinite() {
			return 0, false, false
		}
		return  / 100, true, true
	}

	// calc(...)
	if ,  := strings.CutPrefix(, "calc(");  {
		if ,  := strings.CutSuffix(, ")");  {
			if ,  := eval(, );  && isFinite() {
				return , true, false
			}
		}
	}

	// invalid value
	return 0, false, false
}

// parseNumber parses a decimal floating-point number. strconv.ParseFloat is
// more permissive than wanted here (it accepts digit-separating underscores
// and hex floats such as "0x1p3"), so those forms are rejected up front.
// An out-of-range value parses successfully as ±Inf (strconv.ErrRange)
// instead of failing; callers reject non-finite values.
func parseNumber( string) (float64, bool) {
	if strings.Contains(, "_") {
		return 0, false
	}
	 := 
	if len() > 0 && ([0] == '+' || [0] == '-') {
		 = [1:]
	}
	if len() >= 2 && [0] == '0' && [1] == 'x' { // input is lowercase
		return 0, false
	}

	,  := strconv.ParseFloat(, 64)
	if  != nil && !errors.Is(, strconv.ErrRange) {
		return 0, false
	}
	return , true
}

func isFinite( float64) bool {
	return !math.IsNaN() && !math.IsInf(, 0)
}