
// Main Campaigns App

const { useState, useMemo, useEffect } = React;

// Simple Authentication Wrapper Component
function SimpleAuthWrapper({ children }) {
  const [authState, setAuthState] = useState({
    loading: true,
    authenticated: false,
    user: null,
    error: null
  });
  const [emailInput, setEmailInput] = useState('');

  useEffect(() => {
    // Check if user is already authenticated
    const user = window.SimpleAuth.getCurrentUser();
    if (user) {
      setAuthState({
        loading: false,
        authenticated: true,
        user,
        error: null
      });
    } else {
      setAuthState({
        loading: false,
        authenticated: false,
        user: null,
        error: null
      });
    }
  }, []);

  const handleSignIn = (e) => {
    e.preventDefault();
    setAuthState(prev => ({ ...prev, error: null }));
    
    try {
      const user = window.SimpleAuth.signIn(emailInput);
      setAuthState({
        loading: false,
        authenticated: true,
        user,
        error: null
      });
    } catch (error) {
      setAuthState(prev => ({
        ...prev,
        error: error.message
      }));
    }
  };

  const handleSignOut = () => {
    window.SimpleAuth.signOut();
    setEmailInput('');
    setAuthState({
      loading: false,
      authenticated: false,
      user: null,
      error: null
    });
  };

  // Loading state
  if (authState.loading) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#F0F9F4'
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{
            width: '48px',
            height: '48px',
            border: '4px solid #E0E0E0',
            borderTopColor: '#4CAF50',
            borderRadius: '50%',
            animation: 'spin 1s linear infinite',
            margin: '0 auto 16px'
          }}></div>
          <p style={{ color: '#5B6B7A', fontSize: '14px' }}>Loading...</p>
        </div>
      </div>
    );
  }

  // Not authenticated - show login
  if (!authState.authenticated) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#F0F9F4'
      }}>
        <div style={{
          background: '#fff',
          borderRadius: '16px',
          padding: '48px',
          maxWidth: '440px',
          width: '90%',
          boxShadow: '0 4px 24px rgba(0,0,0,0.08)',
          textAlign: 'center'
        }}>
          <div style={{
            width: '64px',
            height: '64px',
            background: 'linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%)',
            borderRadius: '16px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            margin: '0 auto 24px'
          }}>
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none">
              <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M2 17L12 22L22 17" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M2 12L12 17L22 12" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <h1 style={{
            fontSize: '24px',
            fontWeight: 600,
            color: '#1F2433',
            marginBottom: '8px'
          }}>
            Campaigns - Northstar Fincorp
          </h1>
          <p style={{
            fontSize: '14px',
            color: '#5B6B7A',
            marginBottom: '32px'
          }}>
            Enter your authorized email to continue
          </p>
          {authState.error && (
            <div style={{
              background: '#FFEBEE',
              border: '1px solid #FFCDD2',
              borderRadius: '8px',
              padding: '12px 16px',
              marginBottom: '24px',
              fontSize: '14px',
              color: '#C62828',
              textAlign: 'left'
            }}>
              {authState.error}
            </div>
          )}
          <form onSubmit={handleSignIn} style={{ marginBottom: '24px' }}>
            <input
              type="email"
              value={emailInput}
              onChange={(e) => setEmailInput(e.target.value)}
              placeholder="your.email@zomato.com"
              required
              autoFocus
              style={{
                width: '100%',
                padding: '14px 16px',
                fontSize: '15px',
                border: '1px solid #E0E0E0',
                borderRadius: '8px',
                marginBottom: '16px',
                outline: 'none',
                transition: 'all 0.2s'
              }}
              onFocus={(e) => {
                e.target.style.borderColor = '#4CAF50';
                e.target.style.boxShadow = '0 0 0 3px rgba(76, 175, 80, 0.1)';
              }}
              onBlur={(e) => {
                e.target.style.borderColor = '#E0E0E0';
                e.target.style.boxShadow = 'none';
              }}
            />
            <button
              type="submit"
              style={{
                width: '100%',
                background: 'linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%)',
                border: 'none',
                borderRadius: '8px',
                padding: '14px 24px',
                fontSize: '15px',
                fontWeight: 600,
                color: '#fff',
                cursor: 'pointer',
                transition: 'all 0.2s',
                boxShadow: '0 2px 8px rgba(76, 175, 80, 0.2)'
              }}
              onMouseOver={(e) => {
                e.target.style.boxShadow = '0 4px 12px rgba(76, 175, 80, 0.3)';
                e.target.style.transform = 'translateY(-1px)';
              }}
              onMouseOut={(e) => {
                e.target.style.boxShadow = '0 2px 8px rgba(76, 175, 80, 0.2)';
                e.target.style.transform = 'translateY(0)';
              }}
            >
              Sign In
            </button>
          </form>
          <p style={{
            fontSize: '12px',
            color: '#9E9E9E',
            lineHeight: '1.5'
          }}>
            Only authorized Zomato emails can access this application
          </p>
        </div>
      </div>
    );
  }

  // Authenticated - show app with user context
  return (
    <div>
      {React.cloneElement(children, { user: authState.user, onSignOut: handleSignOut })}
    </div>
  );
}

function App({ user, onSignOut }) {
  const [data, setData] = useState(window.CAMPAIGNS_DATA);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [sortBy, setSortBy] = useState('created_at');
  const [selectedCampaign, setSelectedCampaign] = useState(null);
  const [showCallModal, setShowCallModal] = useState(false);

  // Listen for Firebase real-time updates
  useEffect(() => {
    const handleCampaignAdded = () => {
      console.log('🔄 Campaign added, refreshing React state...');
      setData({ ...window.CAMPAIGNS_DATA });
    };

    const handleCampaignUpdated = () => {
      console.log('🔄 Campaign updated, refreshing React state...');
      setData({ ...window.CAMPAIGNS_DATA });
    };

    const handleCampaignRemoved = () => {
      console.log('🔄 Campaign removed, refreshing React state...');
      setData({ ...window.CAMPAIGNS_DATA });
    };

    const handleCampaignsReset = () => {
      console.log('🗑️ Campaigns reset to demo data');
      setData({ ...window.CAMPAIGNS_DATA });
    };

    window.addEventListener('firebase:campaign:added', handleCampaignAdded);
    window.addEventListener('firebase:campaign:updated', handleCampaignUpdated);
    window.addEventListener('firebase:campaign:removed', handleCampaignRemoved);
    window.addEventListener('firebase:campaigns:reset', handleCampaignsReset);

    return () => {
      window.removeEventListener('firebase:campaign:added', handleCampaignAdded);
      window.removeEventListener('firebase:campaign:updated', handleCampaignUpdated);
      window.removeEventListener('firebase:campaign:removed', handleCampaignRemoved);
      window.removeEventListener('firebase:campaigns:reset', handleCampaignsReset);
    };
  }, []);

  // Handle refresh button - toggle Dushyant Garg campaign
  const handleRefresh = () => {
    console.log('🔄 Refresh button clicked');
    
    // Create a deep copy of the data
    const newData = {
      campaigns: [...data.campaigns],
      stats: { ...data.stats }
    };

    // Check if Dushyant campaign exists
    const dushyantIndex = newData.campaigns.findIndex(c => c.name === 'Dushyant Garg');
    
    if (dushyantIndex === -1) {
      // Add Dushyant campaign at the beginning
      console.log('➕ Adding Dushyant Garg campaign');
      
      // Create a timestamp that's definitely more recent than any other campaign
      const now = new Date();
      const createdDate = `${now.getDate()} ${now.toLocaleString('en-US', { month: 'short' })}'${now.getFullYear().toString().slice(-2)}, ${now.toLocaleString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true })}`;
      
      // Calculate scheduled time (2 hours from now)
      const scheduledTime = new Date(now.getTime() + 2 * 60 * 60 * 1000);
      const hours = scheduledTime.getHours();
      const minutes = scheduledTime.getMinutes().toString().padStart(2, '0');
      const ampm = hours >= 12 ? 'PM' : 'AM';
      const displayHours = hours % 12 || 12;
      const scheduledTimeStr = `${displayHours}:${minutes} ${ampm}`;
      
      const dushyantCampaign = {
        id: 7,
        name: "Dushyant Garg",
        aiAgent: "Sales Outreach Bot",
        aiAgentLink: "https://example.com/agent/3",
        journeyId: "d88blilb30gs739rifbg",
        journeyVersion: 19,
        totalLeads: 1,
        connectedLeads: 0,
        connectedLeadsPercentage: 0,
        totalCalls: 0,
        connectedCalls: 0,
        connectedCallsPercentage: 0,
        created: createdDate,
        createdBy: "T",
        status: `Call at ${scheduledTimeStr} (in 2 hours)`,
        statusType: "scheduled"
      };
      newData.campaigns.unshift(dushyantCampaign);
      newData.stats.scheduled = 1;
    } else {
      // Remove Dushyant campaign
      console.log('➖ Removing Dushyant Garg campaign');
      newData.campaigns.splice(dushyantIndex, 1);
      newData.stats.scheduled = 0;
    }

    // Update both state and window object
    window.CAMPAIGNS_DATA = newData;
    setData(newData);
    
    console.log('✅ Campaigns count:', newData.campaigns.length);
  };

  // Filter campaigns based on search and status
  const filteredCampaigns = useMemo(() => {
    let campaigns = [...data.campaigns];

    // Apply search filter
    if (search.trim()) {
      const query = search.toLowerCase();
      campaigns = campaigns.filter(c =>
        c.name.toLowerCase().includes(query) ||
        c.aiAgent.toLowerCase().includes(query)
      );
    }

    // Apply status filter
    if (statusFilter) {
      campaigns = campaigns.filter(c => c.statusType === statusFilter);
    }

    return campaigns;
  }, [data.campaigns, search, statusFilter]);

  const handleTriggerCall = (campaign) => {
    setSelectedCampaign(campaign);
    setShowCallModal(true);
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: '#F0F9F4'
    }}>
      {/* Header */}
      <header style={{
        background: '#fff',
        borderBottom: '1px solid #E0E0E0',
        padding: '20px 32px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <div style={{
            width: '40px',
            height: '40px',
            background: 'linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%)',
            borderRadius: '10px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
              <path d="M3 5C3 3.89543 3.89543 3 5 3H8C9.10457 3 10 3.89543 10 5V8C10 9.10457 9.10457 10 8 10H5C3.89543 10 3 9.10457 3 8V5Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M14 5C14 3.89543 14.8954 3 16 3H19C20.1046 3 21 3.89543 21 5V8C21 9.10457 20.1046 10 19 10H16C14.8954 10 14 9.10457 14 8V5Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M3 16C3 14.8954 3.89543 14 5 14H8C9.10457 14 10 14.8954 10 16V19C10 20.1046 9.10457 21 8 21H5C3.89543 21 3 20.1046 3 19V16Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M14 16C14 14.8954 14.8954 14 16 14H19C20.1046 14 21 14.8954 21 16V19C21 20.1046 20.1046 21 19 21H16C14.8954 21 14 20.1046 14 19V16Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div>
            <h1 style={{
              margin: 0,
              fontSize: '24px',
              fontWeight: 600,
              color: '#1F2433',
              lineHeight: '1.2'
            }}>
              Campaigns
            </h1>
            <p style={{
              margin: '2px 0 0 0',
              fontSize: '14px',
              color: '#5B6B7A'
            }}>
              Manage your AI calling campaigns
            </p>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <div style={{
            fontSize: '13px',
            color: '#5B6B7A',
            paddingRight: '12px',
            borderRight: '1px solid #E0E0E0'
          }}>
            {user?.email}
          </div>
          <SearchInput
            value={search}
            onChange={setSearch}
            placeholder="Search campaigns by name"
          />
          <Button
            variant={data.campaigns.some(c => c.name === 'Dushyant Garg') ? "secondary" : "ghost"}
            icon={
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>
              </svg>
            }
            onClick={handleRefresh}
          >
            Refresh
          </Button>
          <Button
            variant="primary"
            icon={
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M8 3.33333V12.6667M3.33333 8H12.6667" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            }
            onClick={() => alert('Create new campaign functionality')}
          >
            Create Campaign
          </Button>
          <button
            onClick={onSignOut}
            style={{
              padding: '10px 16px',
              background: '#fff',
              border: '1px solid #E0E0E0',
              borderRadius: '8px',
              fontSize: '14px',
              fontWeight: 500,
              color: '#5B6B7A',
              cursor: 'pointer',
              transition: 'all 0.2s'
            }}
            onMouseOver={(e) => {
              e.target.style.background = '#F5F5F5';
              e.target.style.borderColor = '#C8C8C8';
            }}
            onMouseOut={(e) => {
              e.target.style.background = '#fff';
              e.target.style.borderColor = '#E0E0E0';
            }}
          >
            Sign Out
          </button>
        </div>
      </header>

      {/* Main Content */}
      <main style={{ padding: '32px' }}>
        {/* Filters Bar */}
        <div style={{
          background: '#fff',
          border: '1px solid #E0E0E0',
          borderRadius: '12px',
          padding: '20px 24px',
          marginBottom: '24px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <span style={{ fontSize: '14px', fontWeight: 500, color: '#5B6B7A' }}>
              Filter by:
            </span>
            <Select
              value={statusFilter}
              onChange={setStatusFilter}
              options={[
                { value: 'running', label: 'Running' },
                { value: 'scheduled', label: 'Scheduled' },
                { value: 'completed', label: 'Completed' },
                { value: 'paused', label: 'Paused' },
                { value: 'cancelled', label: 'Cancelled' },
                { value: 'draft', label: 'Draft' }
              ]}
              placeholder="All Statuses"
              width="160px"
            />
            <Select
              value={sortBy}
              onChange={setSortBy}
              options={[
                { value: 'created_at', label: 'Created at' },
                { value: 'name', label: 'Name' },
                { value: 'leads', label: 'Total Leads' }
              ]}
              placeholder="Sort by"
              width="140px"
            />
          </div>
          <div style={{ fontSize: '14px', color: '#5B6B7A' }}>
            Showing <span style={{ fontWeight: 600, color: '#1F2433' }}>{filteredCampaigns.length}</span> of{' '}
            <span style={{ fontWeight: 600, color: '#1F2433' }}>{data.campaigns.length}</span> campaigns
          </div>
        </div>

        {/* Stats Cards */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(6, 1fr)',
          gap: '16px',
          marginBottom: '24px'
        }}>
          <StatCard
            icon={
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                <path d="M10 18.3333C14.6024 18.3333 18.3333 14.6024 18.3333 10C18.3333 5.39763 14.6024 1.66667 10 1.66667C5.39763 1.66667 1.66667 5.39763 1.66667 10C1.66667 14.6024 5.39763 18.3333 10 18.3333Z" stroke="#2196F3" strokeWidth="1.5"/>
                <path d="M10 5V10L13.3333 11.6667" stroke="#2196F3" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            }
            label="Running"
            value={data.stats.running}
            color="#E3F2FD"
            textColor="#1565C0"
          />
          <StatCard
            icon={
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                <path d="M15.8333 3.33333H4.16667C3.24619 3.33333 2.5 4.07953 2.5 5V15.8333C2.5 16.7538 3.24619 17.5 4.16667 17.5H15.8333C16.7538 17.5 17.5 16.7538 17.5 15.8333V5C17.5 4.07953 16.7538 3.33333 15.8333 3.33333Z" stroke="#FF9800" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                <path d="M13.3333 1.66667V5M6.66667 1.66667V5M2.5 8.33333H17.5" stroke="#FF9800" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            }
            label="Scheduled"
            value={data.stats.scheduled}
            color="#FFF3E0"
            textColor="#E65100"
          />
          <StatCard
            icon={
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                <path d="M10 18.3333C14.6024 18.3333 18.3333 14.6024 18.3333 10C18.3333 5.39763 14.6024 1.66667 10 1.66667C5.39763 1.66667 1.66667 5.39763 1.66667 10C1.66667 14.6024 5.39763 18.3333 10 18.3333Z" stroke="#4CAF50" strokeWidth="1.5"/>
                <path d="M6.66667 10L8.88889 12.2222L13.3333 7.77778" stroke="#4CAF50" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            }
            label="Completed"
            value={data.stats.completed}
            color="#E8F5E9"
            textColor="#2E7D32"
          />
          <StatCard
            icon={
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                <path d="M10 18.3333C14.6024 18.3333 18.3333 14.6024 18.3333 10C18.3333 5.39763 14.6024 1.66667 10 1.66667C5.39763 1.66667 1.66667 5.39763 1.66667 10C1.66667 14.6024 5.39763 18.3333 10 18.3333Z" stroke="#FFC107" strokeWidth="1.5"/>
                <path d="M10 6.66667V10M10 13.3333H10.0083" stroke="#FFC107" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            }
            label="Paused"
            value={data.stats.paused}
            color="#FFF9C4"
            textColor="#F57F17"
          />
          <StatCard
            icon={
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                <path d="M10 18.3333C14.6024 18.3333 18.3333 14.6024 18.3333 10C18.3333 5.39763 14.6024 1.66667 10 1.66667C5.39763 1.66667 1.66667 5.39763 1.66667 10C1.66667 14.6024 5.39763 18.3333 10 18.3333Z" stroke="#F44336" strokeWidth="1.5"/>
                <path d="M12.5 7.5L7.5 12.5M7.5 7.5L12.5 12.5" stroke="#F44336" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            }
            label="Cancelled"
            value={data.stats.cancelled}
            color="#FFEBEE"
            textColor="#C62828"
          />
          <StatCard
            icon={
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                <path d="M11.6667 1.66667H5C4.07953 1.66667 3.33333 2.41286 3.33333 3.33333V16.6667C3.33333 17.5871 4.07953 18.3333 5 18.3333H15C15.9205 18.3333 16.6667 17.5871 16.6667 16.6667V6.66667L11.6667 1.66667Z" stroke="#9E9E9E" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                <path d="M11.6667 1.66667V6.66667H16.6667M13.3333 10.8333H6.66667M13.3333 14.1667H6.66667M8.33333 7.5H6.66667" stroke="#9E9E9E" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            }
            label="Draft"
            value={data.stats.draft}
            color="#F5F5F5"
            textColor="#616161"
          />
        </div>

        {/* Campaigns Table */}
        <div style={{
          background: '#fff',
          border: '1px solid #E0E0E0',
          borderRadius: '12px',
          overflow: 'hidden'
        }}>
          <CampaignTable
            campaigns={filteredCampaigns}
            onTriggerCall={handleTriggerCall}
          />
        </div>
      </main>

      {/* Call Modal */}
      {showCallModal && selectedCampaign && (
        <CallModal
          campaign={selectedCampaign}
          onClose={() => {
            setShowCallModal(false);
            setSelectedCampaign(null);
          }}
        />
      )}
    </div>
  );
}

// Stat Card Component
function StatCard({ icon, label, value, color, textColor }) {
  return (
    <div style={{
      background: '#fff',
      border: '1px solid #E0E0E0',
      borderRadius: '12px',
      padding: '20px',
      display: 'flex',
      flexDirection: 'column',
      gap: '12px'
    }}>
      <div style={{
        width: '40px',
        height: '40px',
        borderRadius: '10px',
        background: color,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        {icon}
      </div>
      <div>
        <div style={{
          fontSize: '28px',
          fontWeight: 700,
          color: textColor,
          lineHeight: '1',
          marginBottom: '4px'
        }}>
          {value}
        </div>
        <div style={{
          fontSize: '13px',
          fontWeight: 500,
          color: '#5B6B7A'
        }}>
          {label}
        </div>
      </div>
    </div>
  );
}

// Render App with Simple Auth Wrapper
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <SimpleAuthWrapper>
    <App />
  </SimpleAuthWrapper>
);

// Add keyframe animation for loading spinner
const style = document.createElement('style');
style.textContent = `
  @keyframes spin {
    to { transform: rotate(360deg); }
  }
`;
document.head.appendChild(style);
