/**
 * Manual Login Flow Test
 * Tests login page without requiring Playwright browser installation
 */

const http = require('http');
const https = require('https');

const BASE_URL = 'http://localhost:9000';

function makeRequest(url, method = 'GET', data = null) {
  return new Promise((resolve, reject) => {
    const urlObj = new URL(url);
    const options = {
      hostname: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.pathname + urlObj.search,
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
      }
    };

    if (data) {
      options.headers['Content-Length'] = Buffer.byteLength(data);
    }

    const req = http.request(options, (res) => {
      let body = '';
      res.on('data', (chunk) => body += chunk);
      res.on('end', () => {
        resolve({
          statusCode: res.statusCode,
          headers: res.headers,
          body: body
        });
      });
    });

    req.on('error', reject);
    if (data) req.write(data);
    req.end();
  });
}

async function testLoginPage(lang) {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`Testing ${lang.toUpperCase()} Login Page: /${lang}/login`);
  console.log('='.repeat(60));

  try {
    const response = await makeRequest(`${BASE_URL}/${lang}/login`);

    console.log(`\nStatus Code: ${response.statusCode}`);
    console.log(`Content Type: ${response.headers['content-type']}`);

    const html = response.body;

    // Check for key UI elements
    const checks = {
      'Logo Image': /logo-horizontal\.jpeg|Mawidi|موعدي/.test(html),
      'Main Heading (h2)': /<h2/.test(html),
      'Google OAuth Button': /Continue with Google|المتابعة مع Google/.test(html),
      'Email Input Field': /<input[^>]*id="email"|<input[^>]*type="text"[^>]*email/.test(html),
      'Submit Button': /<button[^>]*type="submit"/.test(html),
      'Sign Up Link': /href="\/\w+\/signup"|Sign up|التسجيل/.test(html),
      'Privacy Link': /href="\/\w+\/privacy"|Privacy|الخصوصية/.test(html),
      'Terms Link': /href="\/\w+\/terms"|Terms|الشروط/.test(html),
      'OR Divider': /OR|أو/.test(html),
      'OTP Info': /verification code|رمز تحقق/.test(html),
      'Password Toggle': /Use password|استخدم كلمة المرور/.test(html),
    };

    console.log('\nUI Elements Check:');
    Object.entries(checks).forEach(([name, present]) => {
      console.log(`  ${present ? '✅' : '❌'} ${name}`);
    });

    // Check RTL for Arabic
    if (lang === 'ar') {
      const hasRTL = /dir="rtl"/.test(html);
      console.log(`  ${hasRTL ? '✅' : '❌'} RTL Direction`);
    }

    // Check LTR for English
    if (lang === 'en') {
      const hasLTR = /dir="ltr"/.test(html);
      console.log(`  ${hasLTR ? '✅' : '❌'} LTR Direction`);
    }

    // Check for common issues
    console.log('\nSecurity & Best Practices:');
    const securityChecks = {
      'CSRF Token Fetch': /\/api\/csrf/.test(html),
      'Auto-complete Attributes': /autocomplete="email"|autocomplete="current-password"/.test(html),
      'Password Type Hidden': /type="password"/.test(html),
      'Loading State Handling': /Loading\.\.\.|جاري التحميل/.test(html),
    };

    Object.entries(securityChecks).forEach(([name, present]) => {
      console.log(`  ${present ? '✅' : '❌'} ${name}`);
    });

    // Check for specific language content
    console.log('\nLanguage-Specific Content:');
    if (lang === 'ar') {
      console.log(`  ${/تسجيل|دخول/.test(html) ? '✅' : '❌'} Arabic login text`);
      console.log(`  ${/بريدك|البريد/.test(html) ? '✅' : '❌'} Arabic email text`);
      console.log(`  ${/كلمة المرور/.test(html) ? '✅' : '❌'} Arabic password text`);
    } else {
      console.log(`  ${/Sign In|Login/.test(html) ? '✅' : '❌'} English login text`);
      console.log(`  ${/email|Email/.test(html) ? '✅' : '❌'} English email text`);
      console.log(`  ${/password|Password/.test(html) ? '✅' : '❌'} English password text`);
    }

    return { success: true, checks };
  } catch (error) {
    console.error(`\n❌ Error: ${error.message}`);
    return { success: false, error: error.message };
  }
}

async function testAPI(endpoint, method = 'GET', data = null) {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`Testing API: ${method} ${endpoint}`);
  console.log('='.repeat(60));

  try {
    const response = await makeRequest(`${BASE_URL}${endpoint}`, method, data);
    console.log(`Status Code: ${response.statusCode}`);
    console.log(`Response: ${response.body.substring(0, 200)}...`);
    return response;
  } catch (error) {
    console.error(`❌ Error: ${error.message}`);
    return null;
  }
}

async function runAllTests() {
  console.log('\n' + '█'.repeat(60));
  console.log('  MAWIDI LOGIN FLOW TEST SUITE');
  console.log('  Port: 9000');
  console.log('  Timestamp: ' + new Date().toISOString());
  console.log('█'.repeat(60));

  // Test both language versions
  const enResult = await testLoginPage('en');
  const arResult = await testLoginPage('ar');

  // Test CSRF endpoint
  await testAPI('/api/csrf');

  // Generate summary report
  console.log('\n' + '='.repeat(60));
  console.log('SUMMARY REPORT');
  console.log('='.repeat(60));

  const enChecks = enResult.success ? Object.values(enResult.checks).filter(v => v).length : 0;
  const arChecks = arResult.success ? Object.values(arResult.checks).filter(v => v).length : 0;
  const totalChecks = enResult.success ? Object.keys(enResult.checks).length : 0;

  console.log(`\nEnglish Version:`);
  console.log(`  Status: ${enResult.success ? '✅ PASS' : '❌ FAIL'}`);
  console.log(`  Checks Passed: ${enChecks}/${totalChecks}`);

  console.log(`\nArabic Version:`);
  console.log(`  Status: ${arResult.success ? '✅ PASS' : '❌ FAIL'}`);
  console.log(`  Checks Passed: ${arChecks}/${totalChecks}`);

  console.log(`\nOverall Status:`);
  const overallPass = enResult.success && arResult.success && enChecks >= totalChecks * 0.9 && arChecks >= totalChecks * 0.9;
  console.log(`  ${overallPass ? '✅ ALL TESTS PASSED' : '⚠️ SOME TESTS FAILED'}`);

  console.log('\n' + '='.repeat(60));
  console.log('RECOMMENDATIONS');
  console.log('='.repeat(60));

  console.log('\nTo test the full login flow:');
  console.log('1. Open http://localhost:9000/en/login in a browser');
  console.log('2. Open http://localhost:9000/ar/login in a browser');
  console.log('3. Test form submissions with empty fields');
  console.log('4. Test password visibility toggle');
  console.log('5. Test Google OAuth button');
  console.log('6. Test with test account: guqo@mailinator.com');
  console.log('7. Check MailHog at http://localhost:8025 for OTP codes');

  console.log('\nTo run automated tests with screenshots:');
  console.log('1. Install Playwright browsers: npx playwright install');
  console.log('2. Run: npx playwright test tests/e2e/test-login-ui.spec.ts --project=chromium --headed');

  console.log('\n' + '█'.repeat(60) + '\n');
}

// Run tests
runAllTests().catch(console.error);
