use std::rc::{Rc, Weak};
use wasm_bindgen::prelude::*;

pub(crate) struct EffectImpl {
    pub(crate) callback: js_sys::Function,
}

thread_local! {
    static CURRENT_SUBSCRIBER: std::cell::RefCell<Option<Weak<EffectImpl>>> =
        const { std::cell::RefCell::new(None) };
}

pub(crate) fn run_effect(effect_handle: &Rc<EffectImpl>) {
    let weak = Rc::downgrade(effect_handle);
    let prev = CURRENT_SUBSCRIBER.with(|c| c.replace(Some(weak)));
    let result = effect_handle.callback.call0(&JsValue::NULL);
    if let Err(e) = result {
        web_sys::console::error_2(&JsValue::from_str("effect error:"), &e);
    }
    CURRENT_SUBSCRIBER.with(|c| *c.borrow_mut() = prev);
}

pub(crate) fn current_subscriber() -> Option<Weak<EffectImpl>> {
    CURRENT_SUBSCRIBER.with(|c| c.borrow().clone())
}
