/* OLIS KYC Form - 5 Step Investment Account Setup */
(function () {


  const { Button, Input, Card, Badge } = window.OLISDesignSystem_ba3bd8;
  const Icon = window.Icon;
  const i18n = window.i18nConfig;

  function KYCForm({ onClose, onComplete }) {
    const [step, setStep] = React.useState(1);
    const [formData, setFormData] = React.useState({
      fullName: '',
      email: '',
      phone: '',
      country: 'MX',
      idType: 'passport',
      idNumber: '',
      investmentAmount: 10000, // $10k default (user can drag to $1k-$200k range)
      multipleAgreements: false,
      acceptedTerms: false,
      signature: null,
    });

    const [errors, setErrors] = React.useState({});

    const validateEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    const validatePhone = (phone) => /^\+?[0-9\s\-\(\)]{10,}$/.test(phone);

    const canProceed = () => {
      const newErrors = {};

      if (step === 1) {
        if (!formData.fullName?.trim()) newErrors.fullName = 'Required';
        if (!validateEmail(formData.email)) newErrors.email = 'Valid email required';
        if (!validatePhone(formData.phone)) newErrors.phone = 'Valid phone required';
        if (!formData.idNumber?.trim()) newErrors.idNumber = 'Required';
      }

      if (step === 2) {
        if (formData.investmentAmount < 1000 || formData.investmentAmount > 200000) {
          newErrors.investmentAmount = 'Must be $1k-$200k';
        }
      }

      if (step === 3) {
        if (!formData.acceptedTerms) newErrors.terms = 'Must accept terms';
      }

      if (step === 4) {
        if (!formData.signature) newErrors.signature = 'Please sign above';
      }

      setErrors(newErrors);
      return Object.keys(newErrors).length === 0;
    };

    // Step 1: Identity
    function Step1() {
      return (
        <div>
          <h2 style={{ fontSize: 24, fontWeight: 600, marginBottom: 24 }}>{i18n.t('kycStep1Title')}</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <Input
              label={i18n.t('fullNameLabel')}
              placeholder={i18n.t('fullNamePlaceholder')}
              value={formData.fullName}
              onChange={(e) => setFormData({ ...formData, fullName: e.target.value })}
            />
            <Input
              label={i18n.t('emailLabel')}
              type="email"
              placeholder={i18n.t('emailPlaceholder')}
              value={formData.email}
              onChange={(e) => setFormData({ ...formData, email: e.target.value })}
            />
            <Input
              label={i18n.t('phoneLabel')}
              placeholder={i18n.t('phonePlaceholder')}
              value={formData.phone}
              onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
            />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div>
                <label style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-strong)', display: 'block', marginBottom: 8 }}>
                  {i18n.t('countryLabel')}
                </label>
                <select
                  value={formData.country}
                  onChange={(e) => setFormData({ ...formData, country: e.target.value })}
                  style={{
                    width: '100%',
                    padding: '10px 12px',
                    border: '1px solid var(--border-soft)',
                    borderRadius: 'var(--radius-md)',
                    fontFamily: 'inherit',
                    fontSize: 14,
                  }}
                >
                  <option value="MX">México</option>
                  <option value="US">United States</option>
                  <option value="AR">Argentina</option>
                  <option value="CO">Colombia</option>
                </select>
              </div>
              <div>
                <label style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-strong)', display: 'block', marginBottom: 8 }}>
                  {i18n.t('idTypeLabel')}
                </label>
                <select
                  value={formData.idType}
                  onChange={(e) => setFormData({ ...formData, idType: e.target.value })}
                  style={{
                    width: '100%',
                    padding: '10px 12px',
                    border: '1px solid var(--border-soft)',
                    borderRadius: 'var(--radius-md)',
                    fontFamily: 'inherit',
                    fontSize: 14,
                  }}
                >
                  <option value="passport">Passport</option>
                  <option value="national_id">National ID</option>
                  <option value="driver_license">Driver License</option>
                </select>
              </div>
            </div>
            <Input
              label={i18n.t('idNumberLabel')}
              placeholder="ABC123456"
              value={formData.idNumber}
              onChange={(e) => setFormData({ ...formData, idNumber: e.target.value })}
            />
          </div>
        </div>
      );
    }

    // Step 2: Investment Amount
    function Step2() {
      const monthlyReturn = (formData.investmentAmount * 0.05).toFixed(2);
      return (
        <div>
          <h2 style={{ fontSize: 24, fontWeight: 600, marginBottom: 24 }}>{i18n.t('kycStep2Title')}</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div>
              <label style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-strong)', display: 'block', marginBottom: 12 }}>
                {i18n.t('investmentAmountLabel')}: ${formData.investmentAmount.toLocaleString()}
              </label>
              <input
                type="range"
                min="1000"
                max="200000"
                step="1000"
                value={formData.investmentAmount}
                onChange={(e) => setFormData({ ...formData, investmentAmount: parseInt(e.target.value) })}
                style={{ width: '100%', height: 6, borderRadius: 3 }}
              />
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 12, color: 'var(--text-muted)' }}>
                <span>$1k</span>
                <span>$100k</span>
                <span>$200k</span>
              </div>
            </div>

            <Card padding={16} style={{ background: 'var(--surface-inset)', border: '1px solid var(--border-subtle)' }}>
              <div style={{ fontSize: 12, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 8 }}>
                {i18n.t('monthlyReturnLabel')}
              </div>
              <div style={{ fontSize: 32, fontWeight: 600, color: 'var(--brand)', fontFamily: 'var(--font-mono)' }}>
                ${monthlyReturn}
              </div>
            </Card>

            <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
              <input
                type="checkbox"
                checked={formData.multipleAgreements}
                onChange={(e) => setFormData({ ...formData, multipleAgreements: e.target.checked })}
                style={{ width: 18, height: 18, cursor: 'pointer' }}
              />
              <span style={{ fontSize: 14, color: 'var(--text-body)' }}>
                {i18n.t('multipleAgreementsLabel')}
              </span>
            </label>
          </div>
        </div>
      );
    }

    // Step 3: Review Terms
    function Step3() {
      return (
        <div>
          <h2 style={{ fontSize: 24, fontWeight: 600, marginBottom: 24 }}>{i18n.t('kycStep3Title')}</h2>
          <Card padding={20} style={{ background: 'var(--surface-inset)', marginBottom: 20, border: '1px solid var(--border-subtle)' }}>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.6 }}>
              <p>{i18n.t('termsDesc')}</p>
            </div>
          </Card>

          <div style={{
            background: 'var(--surface-canvas)',
            border: '1px solid var(--border-subtle)',
            borderRadius: 'var(--radius-lg)',
            padding: 24,
            marginBottom: 20,
            minHeight: 300,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'var(--text-muted)',
          }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 48, marginBottom: 12 }}>📄</div>
              <div style={{ fontSize: 14, marginBottom: 4 }}>{i18n.t('termsTitle')}</div>
              <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>GPS-II Individual Investment Agreement</div>
              <Button variant="secondary" size="sm" style={{ marginTop: 16 }} onClick={() => {}}>
                {i18n.t('btnDownloadAgreement')}
              </Button>
            </div>
          </div>

          <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer' }}>
            <input
              type="checkbox"
              checked={formData.acceptedTerms}
              onChange={(e) => setFormData({ ...formData, acceptedTerms: e.target.checked })}
              style={{ width: 18, height: 18, cursor: 'pointer', marginTop: 2 }}
            />
            <span style={{ fontSize: 14, color: 'var(--text-body)', lineHeight: 1.5 }}>
              {i18n.t('iUnderstandTerms')}
            </span>
          </label>

          {!formData.acceptedTerms && (
            <div style={{ color: 'var(--red-600)', fontSize: 12, marginTop: 12 }}>
              {i18n.t('formValidationError')}
            </div>
          )}
        </div>
      );
    }

    // Step 4: E-Signature (Canvas-based)
    function Step4() {
      const canvasRef = React.useRef(null);
      const [isSigned, setIsSigned] = React.useState(false);

      React.useEffect(() => {
        const canvas = canvasRef.current;
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
        ctx.lineWidth = 2;

        let isDrawing = false;

        const startDrawing = (e) => {
          isDrawing = true;
          const rect = canvas.getBoundingClientRect();
          const x = e.clientX - rect.left || e.touches?.[0]?.clientX - rect.left;
          const y = e.clientY - rect.top || e.touches?.[0]?.clientY - rect.top;
          ctx.beginPath();
          ctx.moveTo(x, y);
        };

        const draw = (e) => {
          if (!isDrawing) return;
          const rect = canvas.getBoundingClientRect();
          const x = e.clientX - rect.left || e.touches?.[0]?.clientX - rect.left;
          const y = e.clientY - rect.top || e.touches?.[0]?.clientY - rect.top;
          ctx.lineTo(x, y);
          ctx.stroke();
        };

        const stopDrawing = () => {
          isDrawing = false;
          setIsSigned(true);
          // Store signature in form data
          const signatureData = canvas.toDataURL('image/png');
          setFormData({ ...formData, signature: signatureData });
        };

        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('touchstart', startDrawing);
        canvas.addEventListener('touchmove', draw);
        canvas.addEventListener('touchend', stopDrawing);

        return () => {
          canvas.removeEventListener('mousedown', startDrawing);
          canvas.removeEventListener('mousemove', draw);
          canvas.removeEventListener('mouseup', stopDrawing);
          canvas.removeEventListener('touchstart', startDrawing);
          canvas.removeEventListener('touchmove', draw);
          canvas.removeEventListener('touchend', stopDrawing);
        };
      }, [formData]);

      const clearSignature = () => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        setIsSigned(false);
        setFormData({ ...formData, signature: null });
      };

      return (
        <div>
          <h2 style={{ fontSize: 24, fontWeight: 600, marginBottom: 24 }}>{i18n.t('kycStep4Title')}</h2>
          <div style={{ marginBottom: 20 }}>
            <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 12, color: 'var(--text-strong)' }}>
              Sign here:
            </label>
            <canvas
              ref={canvasRef}
              width={400}
              height={200}
              style={{
                border: '2px solid var(--border-soft)',
                borderRadius: 'var(--radius-md)',
                cursor: 'crosshair',
                backgroundColor: 'white',
                width: '100%',
                maxWidth: 400,
              }}
            />
          </div>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', justifyContent: 'space-between' }}>
            <Button
              variant="secondary"
              size="sm"
              onClick={clearSignature}
            >
              Clear
            </Button>
            {isSigned ? (
              <div style={{ fontSize: 14, color: 'var(--brand)', display: 'flex', alignItems: 'center', gap: 8 }}>
                ✓ Signature captured
              </div>
            ) : (
              <div style={{ fontSize: 13, color: 'var(--red-600)', fontWeight: 500 }}>
                Please sign above
              </div>
            )}
          </div>
        </div>
      );
    }

    // Step 5: Confirmation
    function Step5() {
      const refNum = `OMG-${new Date().toISOString().split('T')[0].replace(/-/g, '')}-${Math.floor(Math.random() * 100).toString().padStart(2, '0')}`;
      const monthlyReturn = (formData.investmentAmount * 0.05).toFixed(2);

      return (
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 64, marginBottom: 16 }}>✅</div>
          <h2 style={{ fontSize: 28, fontWeight: 600, marginBottom: 8, color: 'var(--brand)' }}>
            {i18n.t('kycStep5Title')}
          </h2>
          <p style={{ fontSize: 16, color: 'var(--text-muted)', marginBottom: 32 }}>
            {i18n.t('successMessage')}
          </p>

          <Card padding={24} style={{ background: 'var(--surface-inset)', marginBottom: 24, border: '1px solid var(--border-subtle)' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
              <div>
                <div style={{ fontSize: 12, color: 'var(--text-faint)', textTransform: 'uppercase', marginBottom: 8, letterSpacing: '0.1em' }}>
                  {i18n.t('referenceNumber')}
                </div>
                <div style={{ fontSize: 18, fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--text-strong)' }}>
                  {refNum}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 12, color: 'var(--text-faint)', textTransform: 'uppercase', marginBottom: 8, letterSpacing: '0.1em' }}>
                  Investment Amount
                </div>
                <div style={{ fontSize: 18, fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--text-strong)' }}>
                  ${formData.investmentAmount.toLocaleString()}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 12, color: 'var(--text-faint)', textTransform: 'uppercase', marginBottom: 8, letterSpacing: '0.1em' }}>
                  Monthly Return
                </div>
                <div style={{ fontSize: 18, fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--brand)' }}>
                  ${monthlyReturn}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 12, color: 'var(--text-faint)', textTransform: 'uppercase', marginBottom: 8, letterSpacing: '0.1em' }}>
                  Lock Period
                </div>
                <div style={{ fontSize: 18, fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--text-strong)' }}>
                  3 months
                </div>
              </div>
            </div>
          </Card>

          <div style={{ textAlign: 'left', marginBottom: 24 }}>
            <h3 style={{ fontSize: 16, fontWeight: 600, marginBottom: 12 }}>{i18n.t('nextSteps')}</h3>
            <ol style={{ fontSize: 14, color: 'var(--text-body)', lineHeight: 2, paddingLeft: 20 }}>
              <li>Transfer ${formData.investmentAmount} USDT to the provided wallet address</li>
              <li>Your capital will be locked for 3 months</li>
              <li>Monthly returns will be paid to your wallet on the 5th of each month</li>
              <li>An advisor will contact you within 24 hours</li>
            </ol>
          </div>

          <Button
            variant="primary"
            size="lg"
            full
            onClick={() => {
              const finalData = {
                ...formData,
                referenceNumber: refNum,
                investmentAmount: parseInt(formData.investmentAmount),
              };
              onComplete(finalData);
              onClose();
            }}
          >
            Complete & Submit
          </Button>
        </div>
      );
    }

    const currentStep = [Step1, Step2, Step3, Step4, Step5][step - 1];

    return (
      <div style={{ padding: 40, maxWidth: 500, margin: '0 auto' }}>
        {/* Step Indicator */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 32, justifyContent: 'center' }}>
          {[1, 2, 3, 4, 5].map((s) => (
            <div
              key={s}
              style={{
                width: 40,
                height: 40,
                borderRadius: '50%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: 14,
                fontWeight: 600,
                background: s <= step ? 'var(--brand)' : 'var(--border-soft)',
                color: s <= step ? 'white' : 'var(--text-muted)',
              }}
            >
              {s < step ? '✓' : s}
            </div>
          ))}
        </div>

        {/* Form Content */}
        {React.createElement(currentStep)}

        {/* Navigation */}
        {step < 5 && (
          <div style={{ display: 'flex', gap: 12, marginTop: 32, justifyContent: 'space-between' }}>
            <Button
              variant="secondary"
              onClick={() => step > 1 && setStep(step - 1)}
              disabled={step === 1}
            >
              {i18n.t('btnBack')}
            </Button>
            <Button
              variant="primary"
              onClick={() => {
                if (canProceed()) {
                  setStep(step + 1);
                }
              }}
            >
              {i18n.t('btnContinue')}
            </Button>
          </div>
        )}
      </div>
    );
  }

  Object.assign(window, { OLISKYCForm: KYCForm });
})();
