// Bionic Reading — bold the first portion of each word to guide the eye and speed up reading.

window.TOOL_HANDLERS['bionic-reading'] = function BionicReadingTool() {
  const FIXATION_OPTIONS = [
    { value: '1', label: '1' },
    { value: '2', label: '2' },
    { value: '3', label: '3' },
    { value: 'half', label: 'Half' },
  ];

  const [text, setText] = React.useState(
    'Bionic Reading is a method that highlights the most important parts of words to guide your eyes more efficiently through text. The brain can fill in the rest of each word, allowing you to read faster while maintaining comprehension.'
  );
  const [fixation, setFixation] = React.useState('half');
  const [copiedPlain, setCopiedPlain] = React.useState(false);
  const [copiedHtml, setCopiedHtml] = React.useState(false);

  const getBoldCount = React.useCallback((word, fix) => {
    if (!word.length) return 0;
    if (fix === 'half') return Math.ceil(word.length / 2);
    const n = parseInt(fix, 10);
    return Math.min(Math.max(1, n), word.length);
  }, []);

  const processedHtml = React.useMemo(() => {
    if (!text.trim()) return '';
    // Process while preserving whitespace structure
    return text.replace(/\S+/g, (word) => {
      // Separate leading/trailing punctuation from the core word for nicer bolding
      const match = word.match(/^([^a-zA-Z0-9]*)([a-zA-Z0-9]*)(.*)$/);
      if (!match) return word;
      const [, prefix, core, suffix] = match;
      if (!core) return word; // purely punctuation
      const n = getBoldCount(core, fixation);
      const bold = core.slice(0, n);
      const rest = core.slice(n);
      return prefix + '<b>' + bold + '</b>' + rest + suffix;
    });
  }, [text, fixation, getBoldCount]);

  const plainText = React.useMemo(() => {
    // Strip HTML tags for plain copy
    return processedHtml.replace(/<\/?b>/g, '');
  }, [processedHtml]);

  const copyPlain = () => {
    navigator.clipboard.writeText(plainText);
    setCopiedPlain(true);
    setTimeout(() => setCopiedPlain(false), 1500);
  };

  const copyHtml = () => {
    navigator.clipboard.writeText(processedHtml);
    setCopiedHtml(true);
    setTimeout(() => setCopiedHtml(false), 1500);
  };

  return (
    <div className="mini-tool">
      <label className="mini-label">Input text</label>
      <textarea
        className="mini-input mini-textarea"
        style={{ minHeight: 140 }}
        placeholder="Paste or type the text you want to process..."
        value={text}
        onChange={(e) => setText(e.target.value)}
      />

      <div style={{ marginTop: 14 }}>
        <label className="mini-label">Fixation strength (letters to bold)</label>
        <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
          {FIXATION_OPTIONS.map((opt) => (
            <button
              key={opt.value}
              className={'filter-pill' + (fixation === opt.value ? ' active' : '')}
              onClick={() => setFixation(opt.value)}
            >
              {opt.label}
            </button>
          ))}
        </div>
      </div>

      {text.trim() && (
        <div style={{ marginTop: 18 }}>
          <label className="mini-label">Bionic output</label>
          <div
            style={{
              padding: '16px 20px',
              background: 'var(--id-surface)',
              border: '1px solid var(--id-border)',
              borderRadius: 10,
              fontSize: 16,
              lineHeight: 1.8,
              color: 'var(--id-text)',
              whiteSpace: 'pre-wrap',
              wordBreak: 'break-word',
              maxHeight: 400,
              overflowY: 'auto',
            }}
            dangerouslySetInnerHTML={{ __html: processedHtml }}
          />
        </div>
      )}

      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={copyPlain} disabled={!text.trim()}>
          <window.Icon name={copiedPlain ? 'check' : 'doc'} size={16} />
          {copiedPlain ? 'Copied!' : 'Copy plain text'}
        </button>
        <button className="btn btn-primary" onClick={copyHtml} disabled={!text.trim()}>
          <window.Icon name={copiedHtml ? 'check' : 'doc'} size={16} />
          {copiedHtml ? 'Copied!' : 'Copy as HTML'}
        </button>
      </div>
    </div>
  );
};
