import { RefObject, useEffect } from 'react';

// Runtime opt-in via `localStorage.setItem('vojo_mediaDebug', '1')`. Note we
// do NOT gate on `import.meta.env.DEV` — that's `false` in any Vite
// production build (including the APK that Capacitor ships), so the debug
// would never fire on-device. The bundle cost of the logging strings is
// ~200 bytes, acceptable for the diagnostic value.
const LS_KEY = 'vojo_mediaDebug';

const enabled = (): boolean => {
  try {
    return typeof window !== 'undefined' && window.localStorage.getItem(LS_KEY) === '1';
  } catch {
    return false;
  }
};

const safeJson = (v: unknown): string => {
  try {
    return JSON.stringify(v);
  } catch {
    return String(v);
  }
};

export const logMedia = (label: string, payload: unknown): void => {
  if (!enabled()) return;
  // eslint-disable-next-line no-console
  console.log(`[VOJO/${label}] ${safeJson(payload)}`);
};

export const useMediaMeasureDebug = (
  ref: RefObject<HTMLElement | null>,
  deps: unknown[]
): void => {
  useEffect(() => {
    if (!enabled()) return undefined;
    const node = ref.current;
    if (!node) return undefined;
    const measure = () => {
      const r = node.getBoundingClientRect();
      const cs = window.getComputedStyle(node);
      const img = node.querySelector('img');
      const imgRect = img?.getBoundingClientRect();
      const imgCS = img && window.getComputedStyle(img);
      const root = document.body.getBoundingClientRect();
      const chain: unknown[] = [];
      let cur: HTMLElement | null = node;
      let depth = 0;
      while (cur && depth < 10) {
        const cr = cur.getBoundingClientRect();
        const ccs = window.getComputedStyle(cur);
        chain.push({
          depth,
          tag: cur.tagName,
          className: typeof cur.className === 'string' ? cur.className : '',
          x: Math.round(cr.x),
          right: Math.round(cr.right),
          w: Math.round(cr.width),
          overflow: ccs.overflow,
          margin: `${ccs.marginLeft} ${ccs.marginRight}`,
          padding: `${ccs.paddingLeft} ${ccs.paddingRight}`,
          width: ccs.width,
          maxWidth: ccs.maxWidth,
          display: ccs.display,
        });
        cur = cur.parentElement;
        depth += 1;
      }
      // eslint-disable-next-line no-console
      console.log(
        `[VOJO/StreamMediaShell/measure] ${safeJson({
          bubbleRect: {
            x: Math.round(r.x),
            y: Math.round(r.y),
            w: Math.round(r.width),
            h: Math.round(r.height),
            right: Math.round(r.right),
          },
          bubbleCS: {
            width: cs.width,
            height: cs.height,
            maxWidth: cs.maxWidth,
            display: cs.display,
            position: cs.position,
            overflow: cs.overflow,
            border: cs.border,
            boxSizing: cs.boxSizing,
          },
          viewport: {
            innerWidth: window.innerWidth,
            bodyWidth: Math.round(root.width),
          },
          img:
            img && imgRect
              ? {
                  rect: {
                    x: Math.round(imgRect.x),
                    w: Math.round(imgRect.width),
                    h: Math.round(imgRect.height),
                    right: Math.round(imgRect.right),
                  },
                  naturalW: img.naturalWidth,
                  naturalH: img.naturalHeight,
                  cs: imgCS && {
                    width: imgCS.width,
                    height: imgCS.height,
                    objectFit: imgCS.objectFit,
                  },
                }
              : 'no-img',
          ancestors: chain,
        })}`
      );
    };
    measure();
    const img = node.querySelector('img');
    if (!img) return undefined;
    img.addEventListener('load', measure);
    return () => img.removeEventListener('load', measure);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);
};
