// Case Converter — transform text between UPPER, lower, Title, camelCase, snake_case, kebab-case, PascalCase, CONSTANT_CASE, dot.case.

window.TOOL_HANDLERS['case-converter'] = function CaseConverterTool() {
  const [input, setInput] = React.useState('');
  const [mode, setMode] = React.useState('upper');
  const [copied, setCopied] = React.useState(false);

  // Split text into words, preserving nothing but word characters
  const toWords = (str) => {
    // Handle camelCase/PascalCase boundaries, underscores, hyphens, dots, spaces
    return str
      .replace(/([a-z])([A-Z])/g, '$1 $2')   // camelCase -> camel Case
      .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') // XMLParser -> XML Parser
      .replace(/[_\-.\s]+/g, ' ')
      .trim()
      .split(/\s+/)
      .filter(Boolean);
  };

  const converters = {
    upper: (s) => s.toUpperCase(),
    lower: (s) => s.toLowerCase(),
    title: (s) => {
      return s.replace(/\w\S*/g, (w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase());
    },
    camel: (s) => {
      const words = toWords(s);
      if (!words.length) return '';
      return words.map((w, i) =>
        i === 0 ? w.toLowerCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
      ).join('');
    },
    snake: (s) => {
      const words = toWords(s);
      return words.map((w) => w.toLowerCase()).join('_');
    },
    kebab: (s) => {
      const words = toWords(s);
      return words.map((w) => w.toLowerCase()).join('-');
    },
    pascal: (s) => {
      const words = toWords(s);
      return words.map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
    },
    constant: (s) => {
      const words = toWords(s);
      return words.map((w) => w.toUpperCase()).join('_');
    },
    dot: (s) => {
      const words = toWords(s);
      return words.map((w) => w.toLowerCase()).join('.');
    },
  };

  const output = React.useMemo(() => {
    if (!input.trim()) return '';
    const fn = converters[mode];
    // Apply per-line to preserve line breaks
    return input.split('\n').map((line) => fn(line)).join('\n');
  }, [input, mode]);

  const copy = () => {
    navigator.clipboard.writeText(output);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  const modes = [
    { id: 'upper',    label: 'UPPER CASE' },
    { id: 'lower',    label: 'lower case' },
    { id: 'title',    label: 'Title Case' },
    { id: 'camel',    label: 'camelCase' },
    { id: 'snake',    label: 'snake_case' },
    { id: 'kebab',    label: 'kebab-case' },
    { id: 'pascal',   label: 'PascalCase' },
    { id: 'constant', label: 'CONSTANT_CASE' },
    { id: 'dot',      label: 'dot.case' },
  ];

  return (
    <div className="mini-tool">
      <label className="mini-label">Input text</label>
      <textarea
        className="mini-input mini-textarea"
        style={{ minHeight: 120 }}
        placeholder="Paste or type text to convert..."
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 14 }}>
        {modes.map((m) => (
          <button
            key={m.id}
            className={'filter-pill' + (mode === m.id ? ' active' : '')}
            onClick={() => setMode(m.id)}
          >
            {m.label}
          </button>
        ))}
      </div>

      <label className="mini-label" style={{ marginTop: 16 }}>Output</label>
      <textarea
        className="mini-input mini-textarea"
        style={{ minHeight: 120 }}
        readOnly
        value={output}
        placeholder="Converted text will appear here..."
      />

      <div className="cmp-actions">
        <button className="btn btn-primary" onClick={copy} disabled={!output}>
          <window.Icon name={copied ? 'check' : 'doc'} size={16} />
          {copied ? 'Copied!' : 'Copy'}
        </button>
      </div>
    </div>
  );
};
