// ProjectExport — export project data with tickets and logs.
// Provides download and copy functionality for complete project export.

function ProjectExport({ project, filename }) {
  const [showMenu, setShowMenu] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [includeLogs, setIncludeLogs] = useState(true);

  const exportProject = async () => {
    setExporting(true);
    try {
      const response = await fetch(`/dashboard/projects/${project.id || project.project_key}/export?include_logs=${includeLogs}`);
      if (!response.ok) {
        throw new Error('Failed to export project');
      }
      return await response.json();
    } catch (error) {
      console.error('Export failed:', error);
      throw error;
    } finally {
      setExporting(false);
    }
  };

  const downloadJSON = async () => {
    try {
      const data = await exportProject();
      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 || project.name}.json`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      link.remove();
      URL.revokeObjectURL(url);
      setShowMenu(false);
    } catch (error) {
      alert('Export failed: ' + error.message);
    }
  };

  const copyToClipboard = async (event) => {
    try {
      const data = await exportProject();
      const content = JSON.stringify(data, null, 2);
      
      await navigator.clipboard.writeText(content);
      
      // 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);
      setShowMenu(false);
    } catch (error) {
      alert('Copy failed: ' + error.message);
    }
  };

  return (
    <div className="relative">
      <button
        onClick={() => setShowMenu(!showMenu)}
        disabled={exporting}
        className="text-xs px-2 py-1 rounded bg-gray-100 text-gray-600 hover:bg-gray-200 flex items-center gap-1 disabled:opacity-50"
        title="Export project data"
      >
        📦 {exporting ? 'Exporting...' : 'Export'} ▼
      </button>
      
      {showMenu && (
        <div className="absolute right-0 mt-1 w-56 bg-white rounded-md shadow-lg border border-gray-200 z-10">
          <div className="py-2">
            <div className="px-3 py-2 border-b border-gray-100">
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={includeLogs}
                  onChange={(e) => setIncludeLogs(e.target.checked)}
                  className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <span className="text-gray-700">Include job logs</span>
              </label>
            </div>
            <button
              onClick={downloadJSON}
              disabled={exporting}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 disabled:opacity-50"
            >
              📋 Download JSON
            </button>
            <button
              onClick={copyToClipboard}
              disabled={exporting}
              className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 disabled:opacity-50"
            >
              📋 Copy to Clipboard
            </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>
  );
}
