/**
 * License Validation System for MoonUI Pro
 * This ensures that only licensed users can access pro components
 */

interface LicenseData {
  key: string;
  email: string;
  expiresAt?: string;
  features?: string[];
}

class LicenseValidator {
  private static instance: LicenseValidator;
  private licenseData: LicenseData | null = null;
  private validationCache: Map<string, boolean> = new Map();
  private readonly VALIDATION_ENDPOINT = 'https://api.moonui.dev/v1/license/validate';

  private constructor() {
    // Initialize license from environment or stored data
    this.initializeLicense();
  }

  static getInstance(): LicenseValidator {
    if (!LicenseValidator.instance) {
      LicenseValidator.instance = new LicenseValidator();
    }
    return LicenseValidator.instance;
  }

  private initializeLicense(): void {
    // Check environment variables
    const licenseKey = process.env.MOONUI_LICENSE_KEY;
    const licenseEmail = process.env.MOONUI_LICENSE_EMAIL;
    
    if (licenseKey && licenseEmail) {
      this.licenseData = {
        key: licenseKey,
        email: licenseEmail
      };
    }
    
    // Check for license file
    try {
      const fs = require('fs');
      const path = require('path');
      const licensePath = path.join(process.cwd(), '.moonui', 'license.json');
      
      if (fs.existsSync(licensePath)) {
        const fileData = fs.readFileSync(licensePath, 'utf-8');
        this.licenseData = JSON.parse(fileData);
      }
    } catch (error) {
      // Ignore file reading errors in browser environment
    }
  }

  async validateLicense(): Promise<boolean> {
    if (!this.licenseData) {
      console.warn('[MoonUI Pro] No license found. Please run "moonui add <pro-component>" to activate your license.');
      return false;
    }

    // Check cache first
    const cacheKey = `${this.licenseData.key}-${this.licenseData.email}`;
    if (this.validationCache.has(cacheKey)) {
      return this.validationCache.get(cacheKey)!;
    }

    // Check expiration date if available
    if (this.licenseData.expiresAt) {
      const expiryDate = new Date(this.licenseData.expiresAt);
      if (expiryDate < new Date()) {
        console.error('[MoonUI Pro] License has expired. Please renew your subscription.');
        this.validationCache.set(cacheKey, false);
        return false;
      }
    }

    // Validate with server (with fallback for offline mode)
    try {
      const response = await fetch(this.VALIDATION_ENDPOINT, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          key: this.licenseData.key,
          email: this.licenseData.email,
        }),
      });

      if (response.ok) {
        const result = await response.json();
        const isValid = result.valid === true;
        this.validationCache.set(cacheKey, isValid);
        
        if (!isValid) {
          console.error('[MoonUI Pro] Invalid license. Please check your license key and email.');
        }
        
        return isValid;
      }
    } catch (error) {
      // Fallback for offline mode or network errors
      // Allow usage if license format is valid
      const isValidFormat = this.isValidLicenseFormat();
      this.validationCache.set(cacheKey, isValidFormat);
      return isValidFormat;
    }

    return false;
  }

  private isValidLicenseFormat(): boolean {
    if (!this.licenseData) return false;
    
    // Basic format validation
    const { key, email } = this.licenseData;
    return (
      typeof key === 'string' &&
      key.length >= 32 &&
      typeof email === 'string' &&
      email.includes('@')
    );
  }

  hasFeature(feature: string): boolean {
    if (!this.licenseData || !this.licenseData.features) {
      return false;
    }
    return this.licenseData.features.includes(feature);
  }

  getLicenseInfo(): Readonly<LicenseData> | null {
    return this.licenseData ? { ...this.licenseData } : null;
  }
}

// Export singleton instance
export const licenseValidator = LicenseValidator.getInstance();

// Higher-order component for license protection
export function withLicenseProtection<P extends object>(
  Component: React.ComponentType<P>,
  componentName: string
): React.ComponentType<P> {
  return (props: P) => {
    const [isValid, setIsValid] = React.useState<boolean | null>(null);

    React.useEffect(() => {
      licenseValidator.validateLicense().then(setIsValid);
    }, []);

    if (isValid === null) {
      // Loading state
      return null;
    }

    if (!isValid) {
      if (process.env.NODE_ENV === 'development') {
        console.error(
          `[MoonUI Pro] Component "${componentName}" requires a valid Pro license.\n` +
          'Get your license at: https://moonui.dev/pricing'
        );
      }
      
      // Return a placeholder in production
      return (
        <div className="rounded-lg border-2 border-dashed border-gray-300 p-4 text-center">
          <p className="text-sm text-gray-500">
            This component requires a MoonUI Pro license.
          </p>
        </div>
      );
    }

    return <Component {...props} />;
  };
}

// Export React for component usage
import * as React from 'react';