import React from "react"; import CopyBtn from "@/components/ui/copy-button"; import { cn } from "@/lib/utils"; import Markdown from "react-markdown"; import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"; import { dracula } from "react-syntax-highlighter/dist/cjs/styles/prism"; import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; function PreWithCopyBtn({ className, ...props }: React.ComponentProps<"pre">) { const ref = React.useRef(null); return ( { return ref.current?.textContent ?? ""; }} />
    
  );
}

export function MarkdownReadonly({
  children: markdown,
  className,
  onSave,
}: {
  children: string;
  className?: string;
  onSave?: (markdown: string) => void;
}) {
  /**
   * This method is triggered when a checkbox is toggled from the masonry view
   * It finds the index of the clicked checkbox inside of the note
   * It then finds the corresponding markdown and changes it accordingly
   */
  const handleTodoClick = (e: React.ChangeEvent) => {
    e.preventDefault();
    const parent = e.target.closest(".prose");
    if (!parent) return;
    const allCheckboxes = parent.querySelectorAll(".todo-checkbox");
    let checkboxIndex = 0;
    allCheckboxes.forEach((cb, i) => {
      if (cb === e.target) checkboxIndex = i;
    });
    let i = 0;
    const todoPattern = /^(\s*[-*+]\s*\[)( |x|X)(\])/gm;
    const newMarkdown = markdown.replace(
      todoPattern,
      (match, prefix: string, state: string, suffix: string) => {
        const currentIndex = i++;
        if (currentIndex !== checkboxIndex) {
          return match;
        }
        const isDone = state.toLowerCase() === "x";
        const nextState = isDone ? " " : "x";
        return `${prefix}${nextState}${suffix}`;
      },
    );
    if (onSave) {
      onSave(newMarkdown);
    }
  };

  return (
    
          props.type === "checkbox" ? (
            
          ) : (
            
          ),
        pre({ ...props }) {
          return ;
        },
        code({ className, children, ...props }) {
          const match = /language-(\w+)/.exec(className ?? "");
          return match ? (
            
              {String(children).replace(/\n$/, "")}
            
          ) : (
            
              {children}
            
          );
        },
      }}
    >
      {markdown}
    
  );
}