"use client";

// The CRM Inbox, rendered by @insignia/iios-messaging-ui instead of the bespoke in-CRM inbox.
// Live = the be-crm data door (CrmInboxAdapter over crm.inbox.* + crm.mail.*); demo = the SDK's
// MockInboxAdapter.

import { useMemo } from "react";
import { useAppShell } from "@abe-kap/appshell-sdk/react";
import { InboxProvider, Inbox as SdkInbox, type InboxAdapter } from "@insignia/iios-messaging-ui";
import { MockInboxAdapter } from "@insignia/iios-messaging-ui/adapters/mock-inbox";
import "@insignia/iios-messaging-ui/styles.css";
import { isShellConfigured } from "@/lib/appshell";
import { CrmInboxAdapter } from "@/lib/crm-inbox-adapter";
import type { DataDoor } from "@/lib/crm-messaging-adapter";

const SHELL = isShellConfigured();

export function InboxSdk({ focusThreadId }: { focusThreadId?: string | null } = {}) {
  return (
    <div className="view">
      {!SHELL && (
        <div style={{ margin: "0 0 14px", padding: "8px 14px", borderRadius: 10, background: "var(--panel-2)", color: "var(--muted)", fontSize: 13, border: "1px solid var(--border)" }}>
          Demo mode — running on the SDK&apos;s mock inbox adapter.
        </div>
      )}
      <div className="miu-host miu-host-inbox">{SHELL ? <LiveInbox focusThreadId={focusThreadId} /> : <DemoInbox focusThreadId={focusThreadId} />}</div>
    </div>
  );
}

function DemoInbox({ focusThreadId }: { focusThreadId?: string | null }) {
  const adapter = useMemo<InboxAdapter>(() => new MockInboxAdapter(), []);
  return (
    <InboxProvider adapter={adapter}>
      <SdkInbox focusThreadId={focusThreadId} />
    </InboxProvider>
  );
}

function LiveInbox({ focusThreadId }: { focusThreadId?: string | null }) {
  const { sdk } = useAppShell();
  const adapter = useMemo<InboxAdapter>(() => new CrmInboxAdapter(sdk as unknown as DataDoor), [sdk]);
  return (
    <InboxProvider adapter={adapter}>
      <SdkInbox focusThreadId={focusThreadId} />
    </InboxProvider>
  );
}
