"use client";

import { type Editor } from "@tiptap/react";

interface CharacterCountProps {
  editor: Editor | null;
  limit?: number;
}

/**
 * Footer bar showing live character and word counts. Requires the
 * @tiptap/extension-character-count extension to be registered on the
 * editor (see TextEditor.tsx).
 */
export default function CharacterCount({ editor, limit = 0 }: CharacterCountProps) {
  if (!editor) return null;

  const characters: number = editor.storage.characterCount?.characters?.() ?? 0;
  const words: number = editor.storage.characterCount?.words?.() ?? 0;
  const hasLimit = limit > 0;
  const percentage = hasLimit ? Math.min(100, (characters / limit) * 100) : 0;
  const isNearLimit = hasLimit && percentage > 90;
  const isOverLimit = hasLimit && characters > limit;

  return (
    <div
      className="
        flex flex-wrap items-center justify-end gap-2 sm:gap-3 border-t
        border-zinc-200 px-3 py-1.5 text-[11px] sm:text-xs text-zinc-400
        
      "
    >
      <span>{words} words</span>
      <span className="text-zinc-300 ">|</span>
      <span
        className={
          isOverLimit
            ? "font-medium text-red-500"
            : isNearLimit
            ? "font-medium text-amber-500"
            : ""
        }
      >
        {hasLimit ? `${characters} / ${limit}` : `${characters}`} characters
      </span>
    </div>
  );
}
