// Legacy Gift Commitment Form - React Component
(function() {
    'use strict';

    if (typeof React === 'undefined' || typeof ReactDOM === 'undefined') {
        console.error('React or ReactDOM not loaded!');
        return;
    }

    const { useState, useEffect } = React;

    function LegacyGiftForm() {
        // State for dynamic names
        const [names, setNames] = useState(['']);

        // Update hidden realname field whenever names change
        useEffect(() => {
            const realnameField = document.querySelector('input[name="realname"]');
            if (realnameField) {
                const formattedNames = names
                    .filter(name => name.trim() !== '')
                    .map((name, index) => `${index + 1}. ${name}`)
                    .join(', ');
                realnameField.value = formattedNames;
            }
        }, [names]);

        // State for gift type sections
        const [giftTypes, setGiftTypes] = useState({
            intendedBequest: false,
            charitableTrust: false,
            iraRetirement: false,
            lifeInsurance: false
        });

        // State for anonymous checkbox
        const [isAnonymous, setIsAnonymous] = useState(false);

        // Name field handlers
        const addName = () => {
            if (names.length < 5) {
                setNames([...names, '']);
            }
        };

        const removeName = (index) => {
            if (names.length > 1) {
                setNames(names.filter((_, i) => i !== index));
            }
        };

        const updateName = (index, value) => {
            const updated = [...names];
            updated[index] = value;
            setNames(updated);
        };

        // Gift type toggle handler
        const toggleGiftType = (type) => {
            setGiftTypes({ ...giftTypes, [type]: !giftTypes[type] });
        };

        return (
            <div className="legacy-gift-form">

                {/* Introduction Text */}
                <div className="form-intro mb-4">
                    <p className="lead">
                        I/we have included the University of West Georgia in my/our estate plans by naming the
                        University of West Georgia Foundation ("UWGF") as beneficiary of my/our assets.
                    </p>
                </div>

                {/* Names on Estate Document - Dynamic Fields */}
                <fieldset className="mb-4">
                    <legend className="h5 mb-3">Name(s) on Estate Document <span className="text-danger" aria-label="required">*</span></legend>

                    <div className="names-container" role="group" aria-label="Names on estate document">
                        {names.map((name, index) => (
                            <div key={index} className="form-group mb-3">
                                <div className="row align-items-end">
                                    <div className="col-md-10">
                                        <label htmlFor={`name-${index}`} className="form-control-label">
                                            {names.length > 1 ? `Name ${index + 1}` : 'Name'}
                                            <span className="text-danger" aria-label="required">*</span>
                                        </label>
                                        <input
                                            id={`name-${index}`}
                                            className="form-control"
                                            name={`names[${index}]`}
                                            type="text"
                                            value={name}
                                            onChange={(e) => updateName(index, e.target.value)}
                                            placeholder="Enter full name"
                                            required={index === 0}
                                            aria-required={index === 0 ? "true" : "false"}
                                        />
                                    </div>
                                    <div className="col-md-2">
                                        {names.length > 1 && (
                                            <button
                                                type="button"
                                                onClick={() => removeName(index)}
                                                className="btn btn-danger btn-sm w-100"
                                                aria-label={`Remove name ${index + 1}`}
                                            >
                                                Remove
                                            </button>
                                        )}
                                    </div>
                                </div>
                            </div>
                        ))}

                        {names.length < 5 && (
                            <button
                                type="button"
                                onClick={addName}
                                className="btn btn-primary btn-sm"
                                aria-label="Add another name"
                            >
                                <span aria-hidden="true">+</span> Add Another Name
                            </button>
                        )}
                    </div>
                </fieldset>

                <hr className="my-4" />

                {/* Gift Arrangement Section */}
                <fieldset className="mb-4">
                    <legend className="h5 mb-3">My/our gift arrangement is described as follows <span className="text-danger" aria-label="required">*</span>:</legend>
                    <p className="text-muted small mb-3">Please select at least one gift type and provide details.</p>

                    {/* Intended Bequest */}
                    <div className="card mb-3">
                        <div className="card-header">
                            <div className="form-check">
                                <input
                                    className="form-check-input"
                                    type="checkbox"
                                    id="gift-intended-bequest"
                                    name="gift_type[]"
                                    value="intended_bequest"
                                    checked={giftTypes.intendedBequest}
                                    onChange={() => toggleGiftType('intendedBequest')}
                                    aria-controls="intended-bequest-details"
                                    aria-expanded={giftTypes.intendedBequest}
                                />
                                <label className="form-check-label fw-bold" htmlFor="gift-intended-bequest">
                                    Intended Bequest
                                </label>
                            </div>
                        </div>

                        {giftTypes.intendedBequest && (
                            <div className="card-body" id="intended-bequest-details">
                                <p className="small text-muted mb-3">
                                    UWGF is named as the beneficiary of a bequest in my/our will described as:
                                </p>

                                <div className="form-group mb-3">
                                    <label htmlFor="bequest-specific-cash" className="form-control-label">
                                        Specific Cash/Property
                                    </label>
                                    <input
                                        id="bequest-specific-cash"
                                        className="form-control"
                                        name="bequest_specific_cash"
                                        type="text"
                                        placeholder="Describe specific cash amount or property"
                                    />
                                </div>

                                <div className="row">
                                    <div className="col-md-6">
                                        <div className="form-group mb-3">
                                            <label htmlFor="bequest-percentage" className="form-control-label">
                                                Percentage of Estate
                                            </label>
                                            <input
                                                id="bequest-percentage"
                                                className="form-control"
                                                name="bequest_percentage"
                                                type="text"
                                                placeholder="e.g., 10%"
                                            />
                                        </div>
                                    </div>
                                    <div className="col-md-6">
                                        <div className="form-group mb-3">
                                            <label htmlFor="bequest-approx-value" className="form-control-label">
                                                Approximate Current Value
                                            </label>
                                            <input
                                                id="bequest-approx-value"
                                                className="form-control"
                                                name="bequest_approx_value"
                                                type="text"
                                                placeholder="e.g., $100,000"
                                            />
                                        </div>
                                    </div>
                                </div>

                                <div className="form-group">
                                    <label htmlFor="bequest-other" className="form-control-label">
                                        Other Details
                                    </label>
                                    <textarea
                                        id="bequest-other"
                                        className="form-control"
                                        name="bequest_other"
                                        rows="3"
                                        placeholder="Any additional details about the bequest"
                                    ></textarea>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Charitable Trust */}
                    <div className="card mb-3">
                        <div className="card-header">
                            <div className="form-check">
                                <input
                                    className="form-check-input"
                                    type="checkbox"
                                    id="gift-charitable-trust"
                                    name="gift_type[]"
                                    value="charitable_trust"
                                    checked={giftTypes.charitableTrust}
                                    onChange={() => toggleGiftType('charitableTrust')}
                                    aria-controls="charitable-trust-details"
                                    aria-expanded={giftTypes.charitableTrust}
                                />
                                <label className="form-check-label fw-bold" htmlFor="gift-charitable-trust">
                                    Charitable Trust
                                </label>
                            </div>
                        </div>

                        {giftTypes.charitableTrust && (
                            <div className="card-body" id="charitable-trust-details">
                                <div className="row">
                                    <div className="col-md-6">
                                        <div className="form-group mb-3">
                                            <label htmlFor="trust-created-date" className="form-control-label">
                                                Trust Created On (Date)
                                            </label>
                                            <input
                                                id="trust-created-date"
                                                className="form-control"
                                                name="trust_created_date"
                                                type="date"
                                            />
                                        </div>
                                    </div>
                                    <div className="col-md-6">
                                        <div className="form-group mb-3">
                                            <label htmlFor="trust-name" className="form-control-label">
                                                Trust Name
                                            </label>
                                            <input
                                                id="trust-name"
                                                className="form-control"
                                                name="trust_name"
                                                type="text"
                                                placeholder="Name of the trust"
                                            />
                                        </div>
                                    </div>
                                </div>

                                <div className="form-group mb-3">
                                    <label htmlFor="trust-held-by" className="form-control-label">
                                        Held By (Bank or Trust Company)
                                    </label>
                                    <input
                                        id="trust-held-by"
                                        className="form-control"
                                        name="trust_held_by"
                                        type="text"
                                        placeholder="Bank or trust company name"
                                    />
                                </div>

                                <div className="form-group mb-3">
                                    <label htmlFor="trust-distribution" className="form-control-label">
                                        The distribution is to be:
                                    </label>
                                </div>

                                <div className="form-group mb-3">
                                    <label htmlFor="trust-specific-annual" className="form-control-label">
                                        Specific Amount Annually
                                    </label>
                                    <input
                                        id="trust-specific-annual"
                                        className="form-control"
                                        name="trust_specific_annual"
                                        type="text"
                                        placeholder="e.g., $5,000 annually"
                                    />
                                </div>

                                <div className="form-group mb-3">
                                    <label htmlFor="trust-remainder" className="form-control-label">
                                        From the Remainder of the Trust
                                    </label>
                                    <input
                                        id="trust-remainder"
                                        className="form-control"
                                        name="trust_remainder"
                                        type="text"
                                        placeholder="Details about remainder distribution"
                                    />
                                </div>

                                <div className="form-group">
                                    <label htmlFor="trust-other" className="form-control-label">
                                        Other Distribution Details
                                    </label>
                                    <textarea
                                        id="trust-other"
                                        className="form-control"
                                        name="trust_other"
                                        rows="3"
                                        placeholder="Any additional distribution details"
                                    ></textarea>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* IRA/Retirement Plan */}
                    <div className="card mb-3">
                        <div className="card-header">
                            <div className="form-check">
                                <input
                                    className="form-check-input"
                                    type="checkbox"
                                    id="gift-ira-retirement"
                                    name="gift_type[]"
                                    value="ira_retirement"
                                    checked={giftTypes.iraRetirement}
                                    onChange={() => toggleGiftType('iraRetirement')}
                                    aria-controls="ira-retirement-details"
                                    aria-expanded={giftTypes.iraRetirement}
                                />
                                <label className="form-check-label fw-bold" htmlFor="gift-ira-retirement">
                                    IRA/Retirement Plan
                                </label>
                            </div>
                        </div>

                        {giftTypes.iraRetirement && (
                            <div className="card-body" id="ira-retirement-details">
                                <p className="small text-muted mb-3">
                                    UWGF is named as a beneficiary of my IRA/Retirement Plan
                                </p>
                                <div className="alert alert-info small" role="alert">
                                    <strong>Helpful tip:</strong> Please share the company name and gift details. For your security, there's no need to include account numbers at this time.
                                </div>

                                <div className="form-group mb-3">
                                    <label htmlFor="ira-company" className="form-control-label">
                                        Company Name
                                    </label>
                                    <input
                                        id="ira-company"
                                        className="form-control"
                                        name="ira_company"
                                        type="text"
                                        placeholder="Financial institution holding the IRA/Retirement Plan"
                                    />
                                </div>

                                <div className="form-group mb-3">
                                    <label htmlFor="ira-specific-cash" className="form-control-label">
                                        Specific Cash Amount
                                    </label>
                                    <input
                                        id="ira-specific-cash"
                                        className="form-control"
                                        name="ira_specific_cash"
                                        type="text"
                                        placeholder="e.g., $50,000"
                                    />
                                </div>

                                <div className="row">
                                    <div className="col-md-6">
                                        <div className="form-group mb-3">
                                            <label htmlFor="ira-percentage" className="form-control-label">
                                                Percentage of Plan Balance
                                            </label>
                                            <input
                                                id="ira-percentage"
                                                className="form-control"
                                                name="ira_percentage"
                                                type="text"
                                                placeholder="e.g., 25%"
                                            />
                                        </div>
                                    </div>
                                    <div className="col-md-6">
                                        <div className="form-group mb-3">
                                            <label htmlFor="ira-approx-value" className="form-control-label">
                                                Approximate Current Value
                                            </label>
                                            <input
                                                id="ira-approx-value"
                                                className="form-control"
                                                name="ira_approx_value"
                                                type="text"
                                                placeholder="e.g., $200,000"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Life Insurance Policy */}
                    <div className="card mb-3">
                        <div className="card-header">
                            <div className="form-check">
                                <input
                                    className="form-check-input"
                                    type="checkbox"
                                    id="gift-life-insurance"
                                    name="gift_type[]"
                                    value="life_insurance"
                                    checked={giftTypes.lifeInsurance}
                                    onChange={() => toggleGiftType('lifeInsurance')}
                                    aria-controls="life-insurance-details"
                                    aria-expanded={giftTypes.lifeInsurance}
                                />
                                <label className="form-check-label fw-bold" htmlFor="gift-life-insurance">
                                    Life Insurance Policy
                                </label>
                            </div>
                        </div>

                        {giftTypes.lifeInsurance && (
                            <div className="card-body" id="life-insurance-details">
                                <p className="small text-muted mb-3">
                                    UWGF is named as the beneficiary of a life insurance policy
                                </p>
                                <div className="alert alert-info small" role="alert">
                                    <strong>Helpful tip:</strong> Please share the company name and policy amount. For your security, there's no need to include policy numbers at this time.
                                </div>

                                <div className="form-group mb-3">
                                    <label htmlFor="insurance-company" className="form-control-label">
                                        Insurance Company Name
                                    </label>
                                    <input
                                        id="insurance-company"
                                        className="form-control"
                                        name="insurance_company"
                                        type="text"
                                        placeholder="Name of insurance company"
                                    />
                                </div>

                                <div className="row">
                                    <div className="col-md-6">
                                        <div className="form-group mb-3">
                                            <label htmlFor="insurance-amount" className="form-control-label">
                                                Policy Amount (Dollars)
                                            </label>
                                            <input
                                                id="insurance-amount"
                                                className="form-control"
                                                name="insurance_amount"
                                                type="text"
                                                placeholder="e.g., $100,000"
                                            />
                                        </div>
                                    </div>
                                    <div className="col-md-6">
                                        <div className="form-group mb-3">
                                            <label htmlFor="insurance-end-date" className="form-control-label">
                                                Policy End Date
                                            </label>
                                            <input
                                                id="insurance-end-date"
                                                className="form-control"
                                                name="insurance_end_date"
                                                type="date"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                </fieldset>

                <hr className="my-4" />

                {/* Purpose of Gift */}
                <div className="form-group mb-4">
                    <label htmlFor="purpose-of-gift" className="form-control-label">
                        Purpose of Gift
                    </label>
                    <textarea
                        id="purpose-of-gift"
                        className="form-control"
                        name="purpose_of_gift"
                        rows="4"
                        placeholder="Please describe how you would like your gift to be used"
                    ></textarea>
                    <small className="form-text text-muted mt-2">
                        *Gifts of $25,000 and more may be restricted for a specific purpose. Gifts of $25,000 and more may be
                        used to create an Endowed Fund. A separate Endowment Agreement will be drafted and entered into
                        with the University of West Georgia Foundation to govern the Fund use in perpetuity.
                    </small>
                </div>

                <hr className="my-4" />

                {/* Anonymous Option */}
                <div className="form-group mb-4">
                    <div className="form-check">
                        <input
                            className="form-check-input"
                            type="checkbox"
                            id="anonymous"
                            name="anonymous"
                            value="yes"
                            checked={isAnonymous}
                            onChange={(e) => setIsAnonymous(e.target.checked)}
                        />
                        <label className="form-check-label" htmlFor="anonymous">
                            I/we would like my/our plans to be anonymous
                        </label>
                    </div>
                </div>

                <hr className="my-4" />

                {/* Signature and Date Section */}
                <fieldset className="mb-4">
                    <legend className="h5 mb-3">Signature(s) and Contact Information</legend>

                    <div className="row">
                        <div className="col-md-8">
                            <div className="form-group mb-3">
                                <label htmlFor="signature1-name" className="form-control-label">
                                    Signature 1 - Full Name <span className="text-danger" aria-label="required">*</span>
                                </label>
                                <input
                                    id="signature1-name"
                                    className="form-control"
                                    name="signature1_name"
                                    type="text"
                                    placeholder="Type your full name as signature"
                                    required
                                    aria-required="true"
                                />
                            </div>
                        </div>
                        <div className="col-md-4">
                            <div className="form-group mb-3">
                                <label htmlFor="signature1-date" className="form-control-label">
                                    Date <span className="text-danger" aria-label="required">*</span>
                                </label>
                                <input
                                    id="signature1-date"
                                    className="form-control"
                                    name="signature1_date"
                                    type="date"
                                    required
                                    aria-required="true"
                                />
                            </div>
                        </div>
                    </div>

                    <div className="row">
                        <div className="col-md-8">
                            <div className="form-group mb-3">
                                <label htmlFor="signature2-name" className="form-control-label">
                                    Signature 2 - Full Name (if applicable)
                                </label>
                                <input
                                    id="signature2-name"
                                    className="form-control"
                                    name="signature2_name"
                                    type="text"
                                    placeholder="Type your full name as signature"
                                />
                            </div>
                        </div>
                        <div className="col-md-4">
                            <div className="form-group mb-3">
                                <label htmlFor="signature2-date" className="form-control-label">
                                    Date
                                </label>
                                <input
                                    id="signature2-date"
                                    className="form-control"
                                    name="signature2_date"
                                    type="date"
                                />
                            </div>
                        </div>
                    </div>

                    <div className="form-group mb-3">
                        <label htmlFor="contact-address" className="form-control-label">
                            Address <span className="text-danger" aria-label="required">*</span>
                        </label>
                        <textarea
                            id="contact-address"
                            className="form-control"
                            name="contact_address"
                            rows="3"
                            placeholder="Full mailing address"
                            required
                            aria-required="true"
                        ></textarea>
                    </div>
                </fieldset>

                <hr className="my-4" />

                {/* Submission Notice */}
                <div className="alert alert-info" role="alert">
                    <p className="mb-0">
                        <strong>Note:</strong> This form and any additional documentation of your plans should be mailed or
                        emailed to the University of West Georgia Foundation, 1601 Maple St., Carrollton, GA 30118 or sent to
                        <a href="mailto:development@westga.edu" className="alert-link"> development@westga.edu</a>.
                    </p>
                </div>

                {/* Security Notice */}
                <div className="alert alert-warning" role="alert">
                    <p className="mb-0">
                        <strong>Please note:</strong> This form is submitted securely via HTTPS, but email is not an encrypted medium.
                        For your protection, please do not include sensitive financial details such as social security numbers,
                        account numbers, or policy numbers. We'll work with you directly to gather those details through secure channels
                        when needed.
                    </p>
                </div>

            </div>
        );
    }

    // Wait for DOM to be ready
    function initForm() {
        const rootElement = document.getElementById('legacy-gift-form-root');

        if (rootElement) {
            const root = ReactDOM.createRoot(rootElement);
            root.render(<LegacyGiftForm />);
        } else {
            console.error('Root element #legacy-gift-form-root not found!');
        }
    }

    // Check if DOM is already loaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initForm);
    } else {
        initForm();
    }

})();
