import React, { useState, useEffect } from 'react';

function App() {
  const [goals, setGoals] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadGoals();
  }, []);

  const loadGoals = async () => {
    setLoading(true);
    try {
      const response = await fetch('/mcp/pipedrive_goals_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({})
      });
      const data = await response.json();
      setGoals(data.data || []);
    } catch (error) {
      console.error('Failed to load goals:', error);
    } finally {
      setLoading(false);
    }
  };

  const calculateProgress = (goal: any) => {
    if (!goal.expected_outcome || goal.expected_outcome.target === 0) return 0;
    const current = goal.expected_outcome.tracking_metric || 0;
    const target = goal.expected_outcome.target;
    return Math.min((current / target) * 100, 100);
  };

  if (loading) {
    return <div className="loading">Loading goals...</div>;
  }

  return (
    <div className="app">
      <header className="header">
        <h1>🎯 Goal Tracker</h1>
        <button onClick={loadGoals} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="goals-list">
        {goals.map(goal => {
          const progress = calculateProgress(goal);
          const isActive = goal.is_active;
          
          return (
            <div key={goal.id} className={`goal-card ${!isActive ? 'inactive' : ''}`}>
              <div className="goal-header">
                <div className="goal-title">{goal.title}</div>
                <div className="goal-status">{isActive ? '🟢 Active' : '⚪ Inactive'}</div>
              </div>
              
              <div className="goal-meta">
                <span>Type: {goal.type?.name || 'N/A'}</span>
                <span>Owner: {goal.owner?.name || 'N/A'}</span>
              </div>

              <div className="progress-section">
                <div className="progress-bar">
                  <div className="progress-fill" style={{ width: `${progress}%` }}></div>
                </div>
                <div className="progress-text">{progress.toFixed(1)}% complete</div>
              </div>

              {goal.expected_outcome && (
                <div className="goal-details">
                  <div className="detail-item">
                    <span>Current:</span>
                    <span>{goal.expected_outcome.tracking_metric || 0}</span>
                  </div>
                  <div className="detail-item">
                    <span>Target:</span>
                    <span>{goal.expected_outcome.target}</span>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default App;
