"use client";

/**
 * Attaches a card's shadow root on browsers that do not do it themselves (task 5.8).
 *
 * Declarative shadow DOM is handled by the HTML parser on every current browser, and this
 * component then finds the work already done and returns. It exists for the ones that leave
 * `<template shadowrootmode>` inert — there the card would silently not appear at all, which
 * is a blank space where the invitation should be.
 *
 * Renders nothing. It is an effect with a component around it, deliberately: the card must
 * not depend on this running, and giving it no output makes that structurally true.
 */
import { useEffect } from "react";

export function ShadowRootFallback({ hostId }: { hostId: string }) {
  useEffect(() => {
    const host = document.getElementById(hostId);
    // Already attached by the parser, which is the normal path — nothing to do.
    if (!host || host.shadowRoot) return;

    const template = host.querySelector("template");
    if (!template) return;

    try {
      host.attachShadow({ mode: "open" }).appendChild(template.content.cloneNode(true));
      template.remove();
    } catch {
      // A host that already has a shadow root, or an element type that cannot take one.
      // Either way the page is still readable — the greeting, date, venue and call to
      // action are all outside the card — so this fails quietly rather than loudly.
    }
  }, [hostId]);

  return null;
}
