/* ---------- Shared asset upload/list util ----------
   Single source of truth for talking to the WHP asset endpoints
   (`upload_asset` / `list_assets`). Behavior is lifted verbatim from the
   `uploadToWhp` helper duplicated across `shared.tsx` / `ImageBlock.tsx` /
   `Logo.tsx` / `Navbar.tsx` / `VideoBlock.tsx` / `FeaturesGrid.tsx` and the
   `list_assets` fetch pattern used in `ImageStylePanel.tsx` / `Logo.tsx` /
   `Navbar.tsx` / `HeroStylePanel.tsx` / `ImageBlock.tsx` / `VideoBlock.tsx`,
   so callers see identical behavior once switched over to this module. */

export interface Asset {
  name: string;
  url: string;
  type: string;
}

/** Upload a file to the WHP asset store. Falls back to a local `blob:` URL
 *  in standalone mode (no `window.WHP_CONFIG`). Returns `null` on failure. */
export async function uploadAsset(file: File): Promise<string | null> {
  const cfg = (window as any).WHP_CONFIG;
  if (!cfg) return URL.createObjectURL(file);
  const formData = new FormData();
  formData.append('file', file);
  try {
    const resp = await fetch(`${cfg.apiUrl}?action=upload_asset&site_id=${cfg.siteId}`, {
      method: 'POST',
      headers: { 'X-CSRF-Token': cfg.csrfToken },
      body: formData,
    });
    const data = await resp.json();
    if (data.success && data.url) return data.url;
    return null;
  } catch { return null; }
}

/** List assets uploaded for the current site, optionally filtered by
 *  media type (matched against the asset's `type` prefix, e.g.
 *  `image/png`.startsWith('image')). Returns `[]` in standalone mode or
 *  on any failure. */
export async function listAssets(mediaType: 'image' | 'video' | 'any' = 'any'): Promise<Asset[]> {
  const cfg = (window as any).WHP_CONFIG;
  if (!cfg) return [];
  try {
    const resp = await fetch(`${cfg.apiUrl}?action=list_assets&site_id=${cfg.siteId}`);
    const data = await resp.json();
    if (!data.success || !Array.isArray(data.assets)) return [];
    if (mediaType === 'any') return data.assets;
    return data.assets.filter((a: any) => (a.type || '').startsWith(mediaType));
  } catch {
    return [];
  }
}
