import { Effect, Layer, SubscriptionRef } from "effect"
import { Component, Lens, ReactRuntime, Subscribable } from "effect-fc-next"
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import "./index.css"


const Counter = Component.make("Counter")(function*() {
    const count = yield* Component.useOnMount(() => Effect.map(
        SubscriptionRef.make(0),
        Lens.fromSubscriptionRef,
    ))
    const [value] = yield* Subscribable.useAll([count])
    const increment = yield* Component.useCallbackSync(
        () => Lens.update(count, n => n + 1),
        [count],
    )

    return (
        <main>
            <h1>Effect FC Next</h1>
            <p>Running on Effect V4.</p>
            <button type="button" onClick={increment}>
                Count: {value}
            </button>
        </main>
    )
})

const runtime = ReactRuntime.make(Layer.empty)
const CounterApp = Counter.pipe(Component.withRuntime(runtime.context))

// biome-ignore lint/style/noNonNullAssertion: the Vite template provides this element
createRoot(document.getElementById("root")!).render(
    <StrictMode>
        <ReactRuntime.Provider runtime={runtime}>
            <CounterApp />
        </ReactRuntime.Provider>
    </StrictMode>,
)
