#!/bin/bash

# Check if a project path is provided
if [ -z "$1" ]; then
  echo "❌ Error: Please provide a path to your React project"
  echo "Usage: ./integrate-sdk.sh /path/to/your/react-project"
  exit 1
fi

REACT_PROJECT_PATH="$1"

# Check if the project path exists
if [ ! -d "$REACT_PROJECT_PATH" ]; then
  echo "❌ Error: The provided path does not exist or is not a directory"
  exit 1
fi

# Check if it's a React project (has package.json with react dependency)
if [ ! -f "$REACT_PROJECT_PATH/package.json" ]; then
  echo "❌ Error: The provided path does not contain a package.json file"
  exit 1
fi

# Build the fixed SDK
echo "📦 Building the fixed SDK..."
cd fixed-sdk
npm install
npm run build
cd ..

# Install the SDK in the React project
echo "📦 Installing the SDK in your React project..."
cd "$REACT_PROJECT_PATH"
npm install --save "$(pwd)/../../realtimecursor/fixed-sdk"

# Create a sample component
echo "📝 Creating a sample component..."
mkdir -p src/components
cat > src/components/CollaborativeEditor.jsx << 'EOL'
import React, { useState, useRef, useEffect } from 'react';
import { useRealtimeCursor, CursorOverlay, CollaboratorsList } from 'realtimecursor-sdk-fixed';
import 'realtimecursor-sdk-fixed/dist/cursor.css';

function CollaborativeEditor() {
  const [content, setContent] = useState('');
  const editorRef = useRef(null);
  
  const { 
    cursors, 
    collaborators,
    connected,
    connect,
    disconnect,
    updateCursor, 
    updateContent
  } = useRealtimeCursor({
    apiUrl: 'http://localhost:3001', // Change this to your backend URL
    projectId: 'your-project-id', // Change this to your project ID
    user: {
      id: `user-${Math.floor(Math.random() * 10000)}`,
      name: `User ${Math.floor(Math.random() * 10000)}`,
      color: getRandomColor()
    }
  });

  // Connect on mount
  useEffect(() => {
    connect();
    return () => disconnect();
  }, [connect, disconnect]);

  // Update cursor position on mouse move
  const handleMouseMove = (e) => {
    if (!editorRef.current) return;
    
    const rect = editorRef.current.getBoundingClientRect();
    updateCursor({
      x: e.clientX,
      y: e.clientY,
      relativeX: e.clientX - rect.left,
      relativeY: e.clientY - rect.top
    });
  };

  // Update content when changed
  const handleContentChange = (e) => {
    const newContent = e.target.value;
    setContent(newContent);
    updateContent(newContent);
  };

  // Generate random color
  function getRandomColor() {
    const colors = [
      '#3b82f6', // blue
      '#ef4444', // red
      '#10b981', // green
      '#f59e0b', // yellow
      '#8b5cf6', // purple
      '#ec4899', // pink
      '#06b6d4', // cyan
      '#f97316', // orange
    ];
    
    return colors[Math.floor(Math.random() * colors.length)];
  }

  return (
    <div className="collaborative-editor">
      <h2>Collaborative Editor</h2>
      
      <div className="connection-status">
        <div className={`status-indicator ${connected ? 'connected' : 'disconnected'}`}></div>
        <div className="status-text">
          {connected ? 'Connected' : 'Disconnected'}
        </div>
      </div>
      
      <div className="editor-container" ref={editorRef} onMouseMove={handleMouseMove}>
        <textarea
          className="editor"
          value={content}
          onChange={handleContentChange}
          placeholder="Start typing..."
        />
        <CursorOverlay cursors={cursors} />
      </div>
      
      <div className="collaborators-panel">
        <h3>Active Collaborators ({collaborators.length})</h3>
        <CollaboratorsList collaborators={collaborators} />
      </div>
    </div>
  );
}

export default CollaborativeEditor;
EOL

# Create CSS for the component
cat > src/components/CollaborativeEditor.css << 'EOL'
.collaborative-editor {
  margin: 20px 0;
}

.editor-container {
  position: relative;
  height: 300px;
  margin-bottom: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  overflow: hidden;
}

.editor {
  width: 100%;
  height: 100%;
  padding: 16px;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
  border: none;
  resize: none;
  outline: none;
  box-sizing: border-box;
}

.collaborators-panel {
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 16px;
}

.connection-status {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.status-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-indicator.connected {
  background-color: #10b981;
}

.status-indicator.disconnected {
  background-color: #ef4444;
}

.status-text {
  font-size: 14px;
  color: #666;
}
EOL

echo "✅ SDK integration complete!"
echo "🎉 You can now import the CollaborativeEditor component in your React app:"
echo ""
echo "import CollaborativeEditor from './components/CollaborativeEditor';"
echo ""
echo "📝 Don't forget to start the backend server:"
echo "cd /path/to/realtimecursor/api"
echo "npm install"
echo "npm start"
echo ""
echo "Happy coding! 🚀"