'use client';

import React, { useState, useEffect } from 'react';

// Replicating the PortalSelection logic for the test component
const portals = {
  general: {
    url: 'https://app.codeframeai.com',
    name: 'General AI Portal',
    cookieValue: 'general'
  },
  education: {
    url: 'https://education.codeframeai.com',
    name: 'Education Portal',
    cookieValue: 'education'
  },
  research: {
    url: 'https://mr.codeframeai.com',
    name: 'Market Research Portal',
    cookieValue: 'research'
  }
};

const getProductsPageUrl = () => {
  return '/products';
};

const setCookie = (name: string, value: string, days: number) => {
  const expires = new Date();
  expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
  
  const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
  let cookieString = `${name}=${value};expires=${expires.toUTCString()};path=/`;
  
  if (!isLocalhost) {
      cookieString += `;domain=.codeframeai.com`;
  }
  
  document.cookie = cookieString;
};

const getCookie = (name: string) => {
  const nameEQ = name + "=";
  const ca = document.cookie.split(';');
  for(let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) === ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
};

const deleteCookie = (name: string) => {
  const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
  let cookieString = `${name}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/`;
  
  if (!isLocalhost) {
      cookieString += `;domain=.codeframeai.com`;
  }
  
  document.cookie = cookieString;
};

export default function TestCookiesPage() {
  const [cookieStatus, setCookieStatus] = useState<React.ReactNode>('Checking...');
  const [selectionResult, setSelectionResult] = useState<React.ReactNode>(null);
  const [flowResult, setFlowResult] = useState<React.ReactNode>(null);

  const checkCookie = () => {
    const portalValue = getCookie('selectedPortal');
    
    if (portalValue && portals[portalValue as keyof typeof portals]) {
      const selectedPortal = portals[portalValue as keyof typeof portals];
      setCookieStatus(
        <>
          <strong>Portal Selected:</strong> {selectedPortal.name}<br />
          <strong>URL:</strong> {selectedPortal.url}<br />
          <strong>Cookie Value:</strong> {selectedPortal.cookieValue}
        </>
      );
    } else {
      setCookieStatus(<strong>No portal selected yet</strong>);
    }
  };

  const handleClearCookie = () => {
    deleteCookie('selectedPortal');
    checkCookie();
    setSelectionResult('Cookie cleared!');
  };

  const testPortalSelection = (portalKey: keyof typeof portals) => {
    const portal = portals[portalKey];
    setSelectionResult(
      <>
        <strong>Would redirect to:</strong> {portal.name}<br />
        <strong>URL:</strong> {portal.url}<br />
        <em>(Note: Not actually redirecting in test mode)</em>
      </>
    );
    
    setCookie('selectedPortal', portal.cookieValue, 365);
    checkCookie();
  };

  const testSignupFlow = () => {
    setFlowResult(
      <>
        <strong>Signup Flow:</strong><br />
        Would redirect to products page: {getProductsPageUrl()}
      </>
    );
  };

  useEffect(() => {
    checkCookie();
  }, []);

  return (
    <div style={{ fontFamily: 'Arial, sans-serif', padding: '20px' }}>
      <h1>Portal Selection Cookie Test</h1>
      
      <div style={{ margin: '20px 0', padding: '15px', border: '1px solid #ddd', borderRadius: '5px' }}>
        <h2>Current Cookie Status</h2>
        <div style={{ margin: '10px 0', padding: '10px', background: '#f5f5f5' }}>
          {cookieStatus}
        </div>
        <button onClick={checkCookie} style={{ margin: '5px', padding: '10px 15px', cursor: 'pointer' }}>Check Cookie</button>
        <button onClick={handleClearCookie} style={{ margin: '5px', padding: '10px 15px', cursor: 'pointer' }}>Clear Cookie</button>
      </div>
      
      <div style={{ margin: '20px 0', padding: '15px', border: '1px solid #ddd', borderRadius: '5px' }}>
        <h2>Test Portal Selection</h2>
        <button onClick={() => testPortalSelection('general')} style={{ margin: '5px', padding: '10px 15px', cursor: 'pointer' }}>Select General Portal</button>
        <button onClick={() => testPortalSelection('education')} style={{ margin: '5px', padding: '10px 15px', cursor: 'pointer' }}>Select Education Portal</button>
        <button onClick={() => testPortalSelection('research')} style={{ margin: '5px', padding: '10px 15px', cursor: 'pointer' }}>Select Research Portal</button>
        <div style={{ margin: '10px 0', padding: '10px', background: '#f5f5f5', display: selectionResult ? 'block' : 'none' }}>
          {selectionResult}
        </div>
      </div>
      
      <div style={{ margin: '20px 0', padding: '15px', border: '1px solid #ddd', borderRadius: '5px' }}>
        <h2>Test Signup Flow</h2>
        <button onClick={testSignupFlow} style={{ margin: '5px', padding: '10px 15px', cursor: 'pointer' }}>Test Handle Signup Flow</button>
        <div style={{ margin: '10px 0', padding: '10px', background: '#f5f5f5', display: flowResult ? 'block' : 'none' }}>
          {flowResult}
        </div>
      </div>
    </div>
  );
}
