# indie:lang_version = 5
from math import isnan
from indie import indicator, MutSeriesF, param, plot, color


@indicator('Coral Trend', overlay_main_pane=True)
@param.int('sm', default=21, min=1, title='Smoothing Period')
@param.float('cd', default=0.4, title='Constant D')
@param.bool('ebc', default=False, title='Color Bars')
@param.bool('ribm', default=False, title='Ribbon Mode')
@plot.marker(
    style=plot.marker_style.CIRCLE,
    position=plot.marker_position.CENTER,
    size=5,
    title='Trend',
)
@plot.background(title='Ribbon')
@plot.bar_color(title='Bar Color')
def Main(self, sm, cd, ebc, ribm):
    src = self.close[0]

    di = (sm - 1.0) / 2.0 + 1.0
    c1 = 2.0 / (di + 1.0)
    c2 = 1.0 - c1
    c3 = 3.0 * (cd * cd + cd * cd * cd)
    c4 = -3.0 * (2.0 * cd * cd + cd + cd * cd * cd)
    c5 = 3.0 * cd + 1.0 + cd * cd * cd + 3.0 * cd * cd

    # Recursive EMA chain (i1 through i6)
    i1 = MutSeriesF.new(init=0.0)
    i1[0] = c1 * src + c2 * i1[0]

    i2 = MutSeriesF.new(init=0.0)
    i2[0] = c1 * i1[0] + c2 * i2[0]

    i3 = MutSeriesF.new(init=0.0)
    i3[0] = c1 * i2[0] + c2 * i3[0]

    i4 = MutSeriesF.new(init=0.0)
    i4[0] = c1 * i3[0] + c2 * i4[0]

    i5 = MutSeriesF.new(init=0.0)
    i5[0] = c1 * i4[0] + c2 * i5[0]

    i6 = MutSeriesF.new(init=0.0)
    i6[0] = c1 * i5[0] + c2 * i6[0]

    # Bandpass filter result
    bfr = MutSeriesF.new(init=0.0)
    prev_bfr = bfr[0]
    bfr[0] = -cd * cd * cd * i6[0] + c3 * i5[0] + c4 * i4[0] + c5 * i3[0]

    # Trend color: green=rising, red=falling, blue=flat
    trend_color = color.BLUE
    if bfr[0] > prev_bfr:
        trend_color = color.GREEN
    elif bfr[0] < prev_bfr:
        trend_color = color.RED

    # Marker: circles when not in ribbon mode
    marker_color = color.TRANSPARENT
    marker_value = self.close[0]
    if not ribm:
        marker_color = color.GRAY if ebc else trend_color
        marker_value = bfr[0]
    marker_result = plot.Marker(value=marker_value, color=marker_color)

    # Background: colored ribbon when in ribbon mode
    bg_color = trend_color(0.5) if ribm else color.TRANSPARENT
    bg_result = plot.Background(color=bg_color)

    # Bar color: color bars when enabled
    bar_c = trend_color if ebc else None
    bar_result = plot.BarColor(color=bar_c)

    return marker_result, bg_result, bar_result
