import { Fragment, useMemo } from 'react';
import { splitTextByOutputPaths } from './output-path-detect';

// Renders plain text with `output/...` paths turned into clickable
// anchors. Used in `<pre>` / `<code>` style contexts that don't go
// through Markdown rendering (Output tab, Subtask instruction blocks).
//
// Markdown contexts use the renderer hooks in markdown-text.tsx
// directly — the resulting HTML is the same shape (`<a class="output-path-link"
// data-output-path="...">`) so the OutputPreviewProvider's delegated
// click listener catches both.

interface LinkifiedTextProps {
  text: string;
  /** Optional className for the wrapping element. Defaults to no styling. */
  className?: string;
  /** Element to wrap the segments in. Defaults to `<span>` — set to `'pre'` etc when caller doesn't already provide its own block. */
  as?: 'span' | 'div' | 'pre';
}

export function LinkifiedText({ text, className, as = 'span' }: LinkifiedTextProps): JSX.Element {
  const segments = useMemo(() => splitTextByOutputPaths(text), [text]);
  const Tag = as as 'span';

  const children = segments.map((seg, i) => {
    if (seg.type === 'text') {
      return <Fragment key={i}>{seg.text}</Fragment>;
    }
    // The OutputPreviewProvider catches the click via event delegation
    // — we deliberately don't attach an onClick here so the behavior is
    // identical to the Markdown-rendered version (which can't have
    // React handlers anyway, since it's dangerouslySetInnerHTML).
    return (
      <a
        key={i}
        className="output-path-link text-blue-600 hover:underline cursor-pointer"
        data-output-path={seg.path}
        role="button"
        tabIndex={0}
      >
        {seg.path}
      </a>
    );
  });

  return <Tag className={className}>{children}</Tag>;
}
