/**
 * Share send/receive for the native shells.
 *  - Receive: the OS hands shared content to the app (Android ACTION_SEND
 *    intent / iOS Share Extension), which the native layer queues; we drain it
 *    here and stash it for the compose/upload flow.
 *  - Send: push content to the OS share sheet via the `share_out` command.
 */
import { invoke } from "@/lib/native/bridge"
import { isTauriRuntime, SUITE_APP } from "@/lib/platform"

export type SharePayload = {
  kind: string
  text?: string | null
  url?: string | null
  files: string[]
  mime?: string | null
}

const PENDING_SHARE_KEY = "ulti-pending-share"

/** Drain a pending inbound share payload (if any). */
export async function takePendingShare(): Promise<SharePayload | null> {
  if (!isTauriRuntime()) return null
  try {
    return (await invoke<SharePayload | null>("plugin:ulti-core|share_take_pending")) ?? null
  } catch {
    return null
  }
}

/** Stash a share payload for the in-app compose/upload flow to pick up. */
export function stashShare(payload: SharePayload) {
  try {
    sessionStorage.setItem(PENDING_SHARE_KEY, JSON.stringify(payload))
  } catch {
    /* ignore */
  }
}

/** Read+clear a stashed share payload (consumed by compose/upload screens). */
export function consumeStashedShare(): SharePayload | null {
  try {
    const raw = sessionStorage.getItem(PENDING_SHARE_KEY)
    if (!raw) return null
    sessionStorage.removeItem(PENDING_SHARE_KEY)
    return JSON.parse(raw) as SharePayload
  } catch {
    return null
  }
}

/** In-app route to land on when content is shared *into* this app. */
export function shareLandingRoute(): string {
  switch (SUITE_APP) {
    case "mail":
      return "/mail/inbox?compose=share"
    case "drive":
      return "/drive?upload=share"
    case "contacts":
      return "/contacts"
    default:
      return "/"
  }
}

/** Share content out to other apps via the OS share sheet. */
export async function shareOut(payload: {
  text?: string
  url?: string
  files?: string[]
  mime?: string
}): Promise<void> {
  if (!isTauriRuntime()) {
    if (navigator.share && (payload.text || payload.url)) {
      await navigator.share({ text: payload.text, url: payload.url })
    }
    return
  }
  await invoke("plugin:ulti-core|share_out", { payload })
}
