import plotly.graph_objects as go


def load_data():
    """Return fitted gains and pointwise 95 percent limits by temperature."""
    return [
        (10, 12, 7, 18),
        (12, 15, 11, 20),
        (14, 19, 15, 23),
        (16, 23, 20, 27),
        (18, 27, 24, 31),
        (20, 30, 27, 34),
        (22, 32, 28, 36),
        (24, 33, 28, 38),
        (26, 33, 27, 40),
        (28, 32, 25, 41),
    ]


def value_table(data):
    return {
        "columns": [
            "Temperature (°C)",
            "Fitted growth (mm)",
            "95% lower limit (mm)",
            "95% upper limit (mm)",
        ],
        "rows": [list(row) for row in data],
    }


def _growth_curve(temperature, estimate, lower, upper, subtitle):
    curve = go.Scatter(
        x=temperature,
        y=estimate,
        mode="lines",
        line={"color": "#22628a", "width": 3},
        customdata=list(zip(lower, upper, strict=True)),
        hovertemplate=(
            "%{x} °C<br>Fitted growth %{y} mm<br>95% interval %{customdata[0]} to "
            "%{customdata[1]} mm<extra></extra>"
        ),
    )
    layout = go.Layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": "Seedling growth by temperature", "subtitle": {"text": subtitle}},
        xaxis={"title": "Temperature (°C)", "dtick": 4},
        yaxis={"title": "Growth (mm)", "range": [0, 45]},
        showlegend=False,
        margin={"l": 62, "r": 24, "t": 78, "b": 60},
    )
    return curve, layout


def make_after(data) -> go.Figure:
    temperature, estimate, lower, upper = zip(*data, strict=True)
    curve, layout = _growth_curve(
        temperature, estimate, lower, upper, "Shading shows pointwise 95% confidence intervals"
    )
    bounds = go.Scatter(
        x=temperature + temperature[::-1],
        y=upper + lower[::-1],
        mode="lines",
        line={"color": "#82a9bf", "width": 1},
        fill="toself",
        fillcolor="rgba(52,122,156,0.2)",
        hoverinfo="skip",
    )
    return go.Figure([bounds, curve], layout)


if __name__ == "__main__":
    print(make_after(load_data()).to_json())
