import { useEffect, useRef } from 'react';

import { useBoard } from '@/data/use-board';

import GlideWidget from './glide-widget';
import { toWidgetPayload } from './widget-payload';

/**
 * Bridges the local task board to the home-screen widget. The app reads the store
 * reactively, so every change to the ready queue is pushed to WidgetKit via
 * `updateSnapshot` — keeping the widget's "NOW" in lockstep with the app whenever
 * it's running, and leaving the last snapshot in place after.
 *
 * `useBoard` is memoised, so its reference only changes when the board's data does;
 * a serialized-payload guard then means we only touch the native module when the
 * rendered content actually changes.
 */
export function useGlideWidgetSync(): void {
  const board = useBoard(48);
  const lastPushed = useRef<string | null>(null);

  useEffect(() => {
    const payload = toWidgetPayload(board);
    const serialized = JSON.stringify(payload);
    if (serialized === lastPushed.current) {
      return;
    }
    // `updateSnapshot` crosses into a native host function that throws on values
    // it can't convert. The widget is peripheral, so a push failure must never
    // take down the app — swallow it (and don't cache, so the next change retries).
    try {
      GlideWidget.updateSnapshot(payload);
      lastPushed.current = serialized;
    } catch (error) {
      if (__DEV__) {
        console.warn('[glide-widget] updateSnapshot failed', error);
      }
    }
  }, [board]);
}
