"use client";

/**
 * NativeCameraButton — render-prop wrapper koji u NATIVE aplikaciji
 * zamenjuje "dodaj fotografiju" kontrolu native kamerom/galerijom
 * (system sheet preko @capacitor/camera). Na web-u `native` je `false`
 * pa pozivni sloj koristi postojeći <input type=file> (web ostaje
 * bajt-identičan; gating preko Capacitor.isNativePlatform()).
 */

import { useEffect, useState } from "react";

import { pickNativePhotos } from "@/lib/native/camera";

export function NativeCameraButton({
  limit,
  onPhotos,
  children,
}: {
  limit: number;
  onPhotos: (files: File[]) => void;
  /** render-prop: ({ native, pick }) → kontrola */
  children: (api: {
    native: boolean;
    pick: () => void;
    busy: boolean;
  }) => React.ReactNode;
}) {
  const [native, setNative] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    let disposed = false;
    (async () => {
      try {
        const { Capacitor } = await import("@capacitor/core");
        if (!disposed && Capacitor.isNativePlatform()) setNative(true);
      } catch {
        /* no-op */
      }
    })();
    return () => {
      disposed = true;
    };
  }, []);

  const pick = async () => {
    if (busy) return;
    setBusy(true);
    try {
      const files = await pickNativePhotos({
        source: "prompt",
        limit,
      });
      if (files.length) onPhotos(files);
    } finally {
      setBusy(false);
    }
  };

  return <>{children({ native, pick: () => void pick(), busy })}</>;
}

export default NativeCameraButton;
