// TableExport — shared export button with CSV/JSON download and clipboard copy.
// Previously duplicated in: tasks.jsx, tools.jsx, models.jsx, tickets/TicketList.jsx

function TableExport({ data, filename, title }) {
  const [showMenu, setShowMenu] = useState(false);

  const convertToCSV = (rows) => {
    if (!rows || rows.length === 0) return '';

    const headers = Object.keys(rows[0]);
    const csvHeaders = headers.join(',');

    const csvRows = rows.map(row => {
      return headers.map(header => {
        const value = row[header];
        // Handle nested objects and arrays
        if (typeof value === 'object' && value !== null) {
          return `"${JSON.stringify(value).replaceAll('"', '""')}"`;
        }
        // Escape commas, quotes, and newlines in strings
        if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n') || value.includes('\r'))) {
          return `"${value.replaceAll('"', '""')}"`;
        }
        return value ?? '';
      }).join(',');
    });

    return [csvHeaders, ...csvRows].join('\n');
  };

  const downloadCSV = () => {
    const csv = convertToCSV(data);
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `${filename}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    link.remove();
  };

  const downloadJSON = () => {
    const json = JSON.stringify(data, null, 2);
    const blob = new Blob([json], { type: 'application/json;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `${filename}.json`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    link.remove();
  };

  const copyToClipboard = (format, event) => {
    let content;
    if (format === 'csv') {
      content = convertToCSV(data);
    } else {
      content = JSON.stringify(data, null, 2);
    }
    
    navigator.clipboard.writeText(content).then(() => {
      // Show brief success feedback
      const button = event.target;
      const originalText = button.textContent;
      button.textContent = 'Copied!';
      button.className = button.className.replace('bg-gray-100', 'bg-green-100').replace('text-gray-600', 'text-green-600');
      setTimeout(() => {
        button.textContent = originalText;
        button.className = button.className.replace('bg-green-100', 'bg-gray-100').replace('text-green-600', 'text-gray-600');
      }, 2000);
    });
  };

  if (!data || data.length === 0) {
    return null;
  }

  return (
    <div className="relative">
      <button
        onClick={() => setShowMenu(!showMenu)}
        className="text-xs px-2 py-1 rounded bg-gray-100 text-gray-600 hover:bg-gray-200 flex items-center gap-1"
        title="Export table data"
      >
        📊 Export ▼
      </button>
      
      {showMenu && (
        <div className="absolute right-0 mt-1 w-48 bg-white rounded-md shadow-lg border border-gray-200 z-10">
          <div className="py-1">
            <button
              onClick={() => { downloadCSV(); setShowMenu(false); }}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              📄 Download CSV
            </button>
            <button
              onClick={() => { downloadJSON(); setShowMenu(false); }}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              📋 Download JSON
            </button>
            <button
              onClick={(e) => { copyToClipboard('csv', e); setShowMenu(false); }}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              📋 Copy CSV
            </button>
            <button
              onClick={(e) => { copyToClipboard('json', e); setShowMenu(false); }}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              📋 Copy JSON
            </button>
          </div>
        </div>
      )}
      
      {/* Close menu when clicking outside */}
      {showMenu && (
        <button
          type="button"
          aria-label="Close export menu"
          className="fixed inset-0 z-0 cursor-default border-0 bg-transparent p-0"
          onClick={() => setShowMenu(false)}
        />
      )}
    </div>
  );
}
