import { cachedMentionContext } from "../lib/mentionContext";
import { formatMentionTimestamp, mentionSurface, type ThreadsMentionHit } from "../lib/mentionInbox";
import { shortText } from "../lib/format";
import type { MediaSnippet } from "../lib/mentionContext";

type Props = {
  hit: ThreadsMentionHit;
};

export function MentionContextBlock({ hit }: Props) {
  const surface = mentionSurface(hit);
  const context = cachedMentionContext(hit);

  if (surface === "post") {
    return (
      <p className="muted hx-text-xs" style={{ margin: 0 }}>
        以下就是對方寫的完整貼文（在貼文中 @ 你）
      </p>
    );
  }

  if (!context || context.status !== "ok") {
    return (
      <div className="hx-mention-context hx-mention-context--error" role="alert">
        <strong>原文暫時無法顯示</strong>
        <span>請重新同步提及清單以快取主串與留言脈絡</span>
      </div>
    );
  }

  return (
    <div className="hx-mention-context" role="region" aria-label="原文脈絡">
      <strong className="hx-mention-context__title">原文脈絡（已快取）</strong>
      {context.root ? <MentionSnippetCard snippet={context.root} /> : null}
      {context.parent ? <MentionSnippetCard snippet={context.parent} /> : null}
      <MentionSnippetCard
        snippet={{
          id: hit.id,
          label: surface === "quote" ? "對方引用並 @ 你的內容" : "對方留言並 @ 你的內容",
          text: hit.text,
          username: hit.username,
          permalink: hit.permalink,
          timestamp: hit.timestamp,
          media_type: hit.media_type
        }}
        highlight
      />
    </div>
  );
}

function MentionSnippetCard({ snippet, highlight = false }: { snippet: MediaSnippet; highlight?: boolean }) {
  return (
    <article className={`hx-mention-snippet${highlight ? " hx-mention-snippet--highlight" : ""}`}>
      <header className="hx-mention-snippet__head">
        <strong>{snippet.label}</strong>
        {snippet.username ? <span className="muted hx-text-xs">@{snippet.username}</span> : null}
        {snippet.timestamp ? <span className="muted hx-text-xs">{formatMentionTimestamp(snippet.timestamp)}</span> : null}
      </header>
      <p className="hx-mention-snippet__text">{snippet.text || shortText(snippet.id, 80)}</p>
      {snippet.permalink ? (
        <a href={snippet.permalink} target="_blank" rel="noreferrer" className="hx-link-chip hx-text-xs">
          開啟這則原文
        </a>
      ) : null}
    </article>
  );
}