export function getSelectedToken() {
  const token = canvas.tokens.controlled[0];
  if (!token) {
    ui.notifications.warn("Please select a token.");
    return null;
  }
  return token;
}

export function findEffect(actor, effectName) {
  return actor.effects.find(e => e.name === effectName);
}

export async function removeEffect(actor, effect) {
  await actor.deleteEmbeddedDocuments("ActiveEffect", [effect.id]);
}

export async function applyEffect(
    actor,
    name,
    icon,
    changes,
    duration = null,
    showIcon = true,
    extraFlags = {}
) {
    const effectData = {
        name,
        icon,
        img: icon,
        origin: null,
        disabled: false,
        duration: duration ? { rounds: duration } : undefined,
        changes,
        statuses: [],
        flags: {
            dae: { showIcon },
            ...extraFlags
        }
    };

    await actor.createEmbeddedDocuments("ActiveEffect", [effectData]);
}

export function notify(message) {
  ui.notifications.info(message);
}

export function postChatMessage(actor, icon, name, enabled = true) {
    const content = `
    <div class="fizzy-chat-card">
      <div class="fizzy-chat-card__header">
        <img class="fizzy-chat-card__icon" src="${icon}" title="${name}" width="36" height="36" />
        <div class="fizzy-chat-card__title">${name}</div>
      </div>
      <div class="fizzy-chat-card__content">
        <p><strong>${name} ${enabled ? "applied" : "removed"}</strong></p>
      </div>
    </div>
  `;

    ChatMessage.create({
        user: game.user.id,
        speaker: ChatMessage.getSpeaker({ actor }),
        style: CONST.CHAT_MESSAGE_STYLES.OTHER,
        content,
        whisper: ChatMessage.getWhisperRecipients("GM").map(u => u.id)
    });
}

export async function runToggleEffect({
    effectName,
    effectIcon,
    changes,
    durationRounds = null,
    showEffectIcon = true,
    showInfoOnEnable = true,
    showInfoOnDisable = true,
    showChatMessage = true,
    effectFlags = {}
}) {
    const token = getSelectedToken();
    if (!token) return;

    const actor = token.actor;
    const existingEffect = findEffect(actor, effectName);

    if (existingEffect) {
        await removeEffect(actor, existingEffect);
        if (showInfoOnDisable) notify(`Removed effect: ${effectName}`);
        if (showChatMessage) postChatMessage(actor, effectIcon, effectName, false);
        return;
    }

    await applyEffect(
        actor,
        effectName,
        effectIcon,
        changes,
        durationRounds,
        showEffectIcon,
        effectFlags
    );

    if (showInfoOnEnable) notify(`Applied effect: ${effectName}`);
    if (showChatMessage) postChatMessage(actor, effectIcon, effectName, true);
}


Hooks.once("init", () => {
  game.fizzy = {
    getSelectedToken,
    findEffect,
    removeEffect,
    applyEffect,
    notify,
    postChatMessage,
    runToggleEffect
  };
  console.log("FizzyBubble: fizzy.js functions registered to game.fizzy");
});