// rithom-intake-widget.js - Simplified form widget using multipart/form-data

class RithomIntake extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.isButtonMode = false;
        this.triggerButton = null;
        this.modalElement = null;
        this.intakeData = null;
        this.formWrapper = null; // Will be the direct container for the form, loading, error states
        this.recaptchaWidgetId = undefined;

        /**
         * @property {Object.<string, function>} fieldRenderers
         * A map of API element types to their corresponding rendering functions.
         * This makes the component easily extensible. Each function is responsible
         * for generating the full semantic HTML for a single form field.
         */
        this.fieldRenderers = {
            'FIRST_NAME': (element) => this._renderInput('text', element),
            'MIDDLE_NAME': (element) => this._renderInput('text', element),
            'LAST_NAME': (element) => this._renderInput('text', element),
            'TEXT': (element) => this._renderInput('text', element),
            'EMAIL': (element) => this._renderInput('email', element),
            'PHONE_NUMBER': (element) => this._renderInput('tel', element),
            'TEXT_PARAGRAPH': this._renderTextarea.bind(this),
            'DATE': (element) => this._renderInput('date', element),
            'FILE_UPLOAD': this._renderFileUpload.bind(this),
            'DROPDOWN': this._renderSelect.bind(this),
        };
    }

    get host() {
        return this.getAttribute('host');
    }

    set host(value) {
        this.setAttribute('host', value);
    }

    get intakeId() {
        return this.getAttribute('intake_id');
    }

    set intakeId(value) {
        this.setAttribute('intake_id', value);
    }

    get password() {
        return this.getAttribute('password');
    }

    set password(value) {
        if (value) {
            this.setAttribute('password', value);
        } else {
            this.removeAttribute('password');
        }
    }

    connectedCallback() {
        this.isButtonMode = this.getAttribute('type') === 'button';
        this._setupInitialDOM(); // Sets up this.formWrapper and modal if needed

        const host = this.getAttribute('host');
        const intakeId = this.getAttribute('intake_id');

        if (!host || !intakeId) {
            const errorDisplayContainer = this.formWrapper || this.shadowRoot;
            this._renderError('Error: Both "host" and "intake_id" attributes are required.', errorDisplayContainer);
            if (this.isButtonMode && this.triggerButton) {
                this.triggerButton.disabled = true;
                this.triggerButton.title = 'Configuration error: host or intake_id missing.';
                this.triggerButton.style.opacity = '0.5';
                this.triggerButton.style.cursor = 'not-allowed';
            }
            return;
        }

        this.host = host;
        this.intakeId = intakeId;

        if (!this.isButtonMode) {
            this._loadAndDisplayForm();
        }
        // For button mode, form loads on button click
    }

    disconnectedCallback() {
        if (this._handleGlobalKeydown) {
            document.removeEventListener('keydown', this._handleGlobalKeydown);
        }
    }

    _setupInitialDOM() {
        this.shadowRoot.innerHTML = `<style>${this._getStyles()}</style>`;

        if (this.isButtonMode) {
            this.triggerButton = document.createElement('button');
            this.triggerButton.textContent = this.getAttribute('button-text') || 'Open Intake Form';
            this.triggerButton.className = 'trigger-button';
            this.triggerButton.style.backgroundColor = this.getAttribute('button-background') || '#2c5282'; // Default from submit
            this.triggerButton.style.color = this.getAttribute('button-color') || 'white';

            this.triggerButton.addEventListener('click', this._handleTriggerButtonClick.bind(this));
            this.shadowRoot.appendChild(this.triggerButton);

            this.modalElement = document.createElement('div');
            this.modalElement.className = 'modal-overlay';
            this.modalElement.style.display = 'none'; // Hidden by default
            this.modalElement.setAttribute('role', 'dialog');
            this.modalElement.setAttribute('aria-modal', 'true');
            this.modalElement.innerHTML = `
        <div class="modal-dialog">
          <div class="modal-header">
            <h2 class="modal-title">${this.getAttribute('form-title') || 'Intake Form'}</h2>
            <button type="button" class="modal-close-button" aria-label="Close modal">&times;</button>
          </div>
          <div class="modal-body"></div>
        </div>
      `;
            this.shadowRoot.appendChild(this.modalElement);
            this.formWrapper = this.modalElement.querySelector('.modal-body');
            this.modalElement.querySelector('.modal-close-button').addEventListener('click', this._hideModal.bind(this));
            this.modalElement.addEventListener('click', (event) => {
                if (event.target === this.modalElement) this._hideModal(); // Click on overlay
            });
            // Add Escape key listener
            this._handleGlobalKeydown = (event) => {
                if (event.key === 'Escape' && this.modalElement.style.display === 'flex') {
                    this._hideModal();
                }
            };
            document.addEventListener('keydown', this._handleGlobalKeydown);
        } else {
            const inlineWrapper = document.createElement('div');
            inlineWrapper.className = 'intake-wrapper';
            this.shadowRoot.appendChild(inlineWrapper);
            this.formWrapper = inlineWrapper;
        }
    }

    /**
     * @typedef {Object} IntakeMetadata
     * @property {string} id
     * @property {string} name
     * @property {string} title
     * @property {boolean} use_password
     * @property {string} create_time
     * @property {string} update_time
     */

    /**
     * @typedef {Object} IntakeElement
     * @property {string} id
     * @property {string} type
     * @property {string} label
     * @property {string} custom_attribute_key
     * @property {boolean} required
     * @property {string} placeholder_text
     * @property {string} help_text
     * @property {string} rank
     * @property {Array<{label: string, value: string}>} [options]
     * @property {Array<string>} [accepted_file_types]
     * @property {boolean} [allow_multiple]
     * @property {number} [rows]
     */

    /**
     * @typedef {Object} IntakeEmbed
     * @property {string} id
     * @property {string} name
     * @property {string} title
     * @property {Array<IntakeElement>} elements
     * @property {boolean} [use_recaptcha]
     * @property {string} [recaptcha_site_key]
     * @property {string} [success_message]
     * @property {string} create_time
     * @property {string} update_time
     */

    /**
     * Fetches metadata to determine if password is required
     * @returns {Promise<IntakeMetadata>}
     */
    async fetchIntakeMetadata() {
        const apiUrl = new URL(`https://${this.host}/api/v1/publicIntakeMetadata/${this.intakeId}`);
        try {
            const response = await fetch(apiUrl.toString());
            if (!response.ok) {
                throw new Error(`API responded with status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            throw new Error(`Failed to fetch intake metadata: ${error.message}`);
        }
    }

    /**
     * Fetches the full intake data, providing password if required
     * @param {string} [password]
     * @returns {Promise<IntakeEmbed>}
     */
    async fetchIntakeData(password = null) {
        const apiUrl = new URL(`https://${this.host}/api/v1/publicIntakes/${this.intakeId}`);

        // Extract the 'password' attribute from the component or query parameter from the current page URL
        const componentPassword = this.getAttribute('password');
        const pageParams = new URLSearchParams(window.location.search);
        const urlPassword = pageParams.get('password');

        if (password) {
            apiUrl.searchParams.set('password', password);
        } else if (componentPassword && componentPassword.trim() !== '') {
            apiUrl.searchParams.set('password', componentPassword);
        } else if (urlPassword) {
            apiUrl.searchParams.set('password', urlPassword);
        }

        const response = await fetch(apiUrl.toString());
        if (!response.ok) {
            if (response.status === 401 || response.status === 403) {
                throw new Error("Invalid password");
            }
            throw new Error(`API responded with status: ${response.status}`);
        }
        return await response.json();
    }

    async _loadAndDisplayForm() {
        if (!this.formWrapper) {
            console.error("Form wrapper not initialized.");
            this._renderError("Form display area not ready.", this.shadowRoot);
            return;
        }
        this._showLoading(this.formWrapper);

        if (this.isButtonMode && this.modalElement) {
            this.modalElement.style.display = 'flex';
        }

        try {
            const metadata = await this.fetchIntakeMetadata();

            if (this.isButtonMode && this.modalElement && metadata?.name) {
                const modalTitle = this.modalElement.querySelector('.modal-title');
                if (modalTitle) modalTitle.textContent = metadata.name;
            }

            if (metadata.use_password) {
                this._renderPasswordPrompt(this.formWrapper, metadata);
            } else {
                await this._loadFullIntakeData();
            }
        } catch (error) {
            console.error('Failed to load metadata:', error);
            this._renderError(error.message || 'Sorry, we could not load the form at this time.', this.formWrapper);
            this.dispatchEvent(new CustomEvent('intake-error', { bubbles: true, composed: true, detail: { error: error.message } }));
        }
    }

    async _loadFullIntakeData(password = null) {
        this._showLoading(this.formWrapper);
        try {
            const data = await this.fetchIntakeData(password);
            this.intakeData = data;
            this._renderFormContent(this.formWrapper);
            this.dispatchEvent(new CustomEvent('intake-loaded', { bubbles: true, composed: true, detail: { intakeId: this.intakeId } }));
        } catch (error) {
            console.error('Failed to load or render form:', error);
            this._renderError(error.message || 'Sorry, we could not load the form at this time.', this.formWrapper);
            this.dispatchEvent(new CustomEvent('intake-error', { bubbles: true, composed: true, detail: { error: error.message } }));
        }
    }

    /**
     * Renders a password prompt for protected intakes
     * @param {HTMLElement} container 
     * @param {IntakeMetadata} metadata 
     * @param {string} [errorMessage]
     */
    _renderPasswordPrompt(container, metadata, errorMessage = '') {
        const titleHtml = !this.isButtonMode ? `<h2>${this._escapeHTML(metadata.name) || 'Protected Intake Form'}</h2>` : '';
        const errorHtml = errorMessage ? `<div class="error" style="margin-bottom: 1rem;">${this._escapeHTML(errorMessage)}</div>` : '';

        container.innerHTML = `
            ${titleHtml}
            ${errorHtml}
            <form class="password-form" novalidate>
                <div class="form-group">
                    <label for="intake-password" class="field-label">Password Required</label>
                    <input type="password" id="intake-password" class="form-input" required placeholder="Enter password">
                </div>
                <button type="submit" class="submit-button">Submit Password</button>
            </form>
        `;

        const form = container.querySelector('.password-form');
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const passwordInput = form.querySelector('#intake-password');
            const submitBtn = form.querySelector('.submit-button');
            const originalText = submitBtn.textContent;

            submitBtn.textContent = 'Verifying...';
            submitBtn.disabled = true;

            try {
                const data = await this.fetchIntakeData(passwordInput.value);
                this.intakeData = data;
                this._renderFormContent(this.formWrapper);
            } catch (err) {
                this._renderPasswordPrompt(container, metadata, err.message === "Invalid password" ? "Incorrect password. Please try again." : err.message);
            }
        });
    }

    _escapeHTML(str) {
        if (typeof str !== 'string') return str;
        return str.replace(/[&<>"']/g, (match) => {
            const escape = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#39;'
            };
            return escape[match];
        });
    }

    // --- HTML Rendering ---

    _showLoading(container) {
        container.innerHTML = `<div class="loading">Loading form...</div>`;
    }

    _renderError(message, container) {
        container.innerHTML = `<div class="error">${message}</div>`;
    }

    _renderFormContent(container) {
        if (!this.intakeData) {
            this._renderError("Form data is not available.", container);
            return;
        }
        const formHtml = this._buildFormHTML();
        container.innerHTML = formHtml;
        if (container.querySelector('.intake-form')) {
            this._attachFormEvents(container);
        }
    }

    _buildFormHTML() {
        if (!this.intakeData?.elements) {
            return '<p class="error">Invalid form data received. Unable to build form.</p>';
        }

        const sortedElements = [...this.intakeData.elements].sort((a, b) => (a.rank < b.rank ? -1 : (a.rank > b.rank ? 1 : 0)));

        const formElementsHtml = sortedElements
            .map(element => {
                const renderer = this.fieldRenderers[element.type];
                return renderer ? renderer(element) : ''; // Render element or ignore if type is unknown
            })
            .join('');

        const recaptchaHtml = this.intakeData.use_recaptcha ?
            '<div class="recaptcha-container" id="recaptcha-container"></div>' : '';

        const titleHtml = !this.isButtonMode ? `<h2>${this._escapeHTML(this.intakeData.name) || 'Intake Form'}</h2>` : '';

        return `
      ${titleHtml}
      <form class="intake-form" novalidate>
        ${formElementsHtml}
        ${recaptchaHtml}
        <button type="submit" class="submit-button">Send Info</button>
        <div class="form-submission-error" role="alert"></div>
      </form>
    `;
    }

    /**
     * Generates the HTML for a standard <input> element.
     * @param {string} type - The input type (e.g., 'text', 'email', 'date').
     * @param {object} element - The configuration object for the element from the API.
     * @returns {string} The complete HTML string for the form group.
     */
    _renderInput(type, element) {
        const fieldName = element.custom_attribute_key || element.id;
        const isRequired = element.required;
        const safeId = this._escapeHTML(element.id);
        const safeName = this._escapeHTML(fieldName);
        const safePlaceholder = this._escapeHTML(element.placeholder_text);

        const inputHtml = `
      <input
        type="${type}"
        id="${safeId}"
        name="${safeName}"
        class="form-input"
        ${isRequired ? 'required aria-required="true"' : ''}
        ${safePlaceholder && safePlaceholder.trim() !== '' ? `placeholder="${safePlaceholder}"` : ''}
      >`;

        return this._wrapInFormGroup(element, inputHtml);
    }

    /**
     * Generates the HTML for a <textarea> element.
     * @param {object} element - The configuration object for the element from the API.
     * @returns {string} The complete HTML string for the form group.
     */
    _renderTextarea(element) {
        const fieldName = element.custom_attribute_key || element.id;
        const isRequired = element.required;
        const safeId = this._escapeHTML(element.id);
        const safeName = this._escapeHTML(fieldName);
        const safePlaceholder = this._escapeHTML(element.placeholder_text);

        const textareaHtml = `
      <textarea
        id="${safeId}"
        name="${safeName}"
        class="form-textarea"
        rows="${element.rows || 4}"
        ${isRequired ? 'required aria-required="true"' : ''}
        ${safePlaceholder && safePlaceholder.trim() !== '' ? `placeholder="${safePlaceholder}"` : ''}
      ></textarea>`;

        return this._wrapInFormGroup(element, textareaHtml);
    }

    /**
     * Generates the HTML for a <select> (dropdown) element.
     * @param {object} element - The configuration object for the element from the API.
     * @returns {string} The complete HTML string for the form group.
     */
    _renderSelect(element) {
        const fieldName = element.custom_attribute_key || element.id;
        const isRequired = element.required;
        const safeId = this._escapeHTML(element.id);
        const safeName = this._escapeHTML(fieldName);
        const safePlaceholder = this._escapeHTML(element.placeholder_text);

        const optionsHtml = (element.options || [])
            .map(option => `<option value="${this._escapeHTML(option.value)}">${this._escapeHTML(option.label)}</option>`)
            .join('');

        const selectHtml = `
      <select
        id="${safeId}"
        name="${safeName}"
        class="form-select"
        ${isRequired ? 'required aria-required="true"' : ''}
      >
        <option value="">${safePlaceholder && safePlaceholder.trim() !== '' ? safePlaceholder : 'Please select...'}</option>
        ${optionsHtml}
      </select>`;

        return this._wrapInFormGroup(element, selectHtml);
    }

    /**
     * Generates the HTML for a file upload <input> element.
     * @param {object} element - The configuration object for the element from the API.
     * @returns {string} The complete HTML string for the form group.
     */
    _renderFileUpload(element) {
        const fieldName = element.custom_attribute_key || element.id;
        const isRequired = element.required;
        const safeId = this._escapeHTML(element.id);
        const safeName = this._escapeHTML(fieldName);

        const fileInputHtml = `
      <input
        type="file"
        id="${safeId}"
        name="${safeName}"
        class="form-file-input"
        ${isRequired ? 'required aria-required="true"' : ''}
        ${element.accepted_file_types ? `accept="${element.accepted_file_types.join(',')}"` : ''}
        ${element.allow_multiple ? 'multiple' : ''}
      >`;

        return this._wrapInFormGroup(element, fileInputHtml);
    }

    /**
     * Wraps an input element in a standard form group structure with a label and help text.
     * This ensures consistency and semantic markup for all fields.
     * @param {object} element - The element configuration.
     * @param {string} inputHtml - The pre-generated HTML for the input itself.
     * @returns {string} The complete HTML string for the form group.
     */
    _wrapInFormGroup(element, inputHtml) {
        const safeId = this._escapeHTML(element.id);
        const safeLabel = this._escapeHTML(element.label);
        const helpTextId = `${safeId}-help`;
        const helpTextHtml = element.help_text && element.help_text.trim() !== '' ?
            `<small id="${helpTextId}" class="help-text">${this._escapeHTML(element.help_text)}</small>` : '';

        return `
      <div class="form-group">
        <label for="${safeId}" class="field-label">
          ${safeLabel}
          ${element.required ? '<span class="required" aria-hidden="true">*</span>' : ''}
        </label>
        ${inputHtml}
        ${helpTextHtml}
      </div>
    `;
    }

    // --- Form Submission & Event Handling ---

    _attachFormEvents(container) {
        const form = container.querySelector('.intake-form');
        if (form) {
            form.addEventListener('submit', this._handleSubmit.bind(this));
        }
        if (this.intakeData?.use_recaptcha && container) {
            const recaptchaDiv = container.querySelector('#recaptcha-container');
            if (recaptchaDiv) {
                this._initializeRecaptcha(recaptchaDiv);
            }
        }
    }

    _handleTriggerButtonClick() {
        if (this.modalElement) {
            this.modalElement.style.display = 'flex';
            // Load or reload form if it's not there or in an error/loading state
            if (!this.intakeData || this.formWrapper.querySelector('.loading, .error')) {
                this._loadAndDisplayForm();
            }
        }
    }
    _hideModal() {
        if (this.modalElement) {
            this.modalElement.style.display = 'none';
        }
    }

    async _handleSubmit(event) {
        event.preventDefault();
        const form = event.target;
        const button = form.querySelector('.submit-button');
        const errorContainer = form.querySelector('.form-submission-error');

        // Basic HTML5 validation check
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }

        const originalText = button.textContent;
        button.textContent = 'Submitting...';
        button.disabled = true;
        if (errorContainer) errorContainer.textContent = '';

        try {
            // Create a FormData object directly from the form.
            // This automatically captures all fields, including files, in the correct format.
            const formData = new FormData(form);

            if (this.intakeData?.use_recaptcha) {
                const recaptchaToken = await this._getRecaptchaToken();
                formData.append('g-recaptcha-response', recaptchaToken); // Standard key for reCAPTCHA v2
            }

            await this._submitToAPI(formData);
            this._showSuccess();
            this.dispatchEvent(new CustomEvent('intake-submitted', { bubbles: true, composed: true, detail: { intakeId: this.intakeId } }));

        } catch (error) {
            console.error('Submission error:', error);
            if (errorContainer) {
                errorContainer.textContent = error.message || 'There was an error submitting your form. Please try again.';
            }
            button.textContent = originalText;
            button.disabled = false;
            this.dispatchEvent(new CustomEvent('intake-error', { bubbles: true, composed: true, detail: { error: error.message } }));
        }
    }

    _fileToBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }

    /**
     * Submits the form data to the API using multipart/form-data encoding.
     * @param {FormData} formData - The FormData object to be submitted.
     */
    async _submitToAPI(formData) {
        const url = `https://${this.host}/api/submit`;
        const formValues = {};

        for (const [key, value] of formData.entries()) {
            if (value instanceof File) {
                if (value.size > 0) {
                    formValues[key] = await this._fileToBase64(value);
                }
            } else {
                formValues[key] = value;
            }
        }

        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                intake_id: this.intakeId,
                data: formValues
            })
        });

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: 'Submission failed with an unknown error.' }));
            throw new Error(errorData.message || `API Error: ${response.status}`);
        }
        return response.json().catch(() => ({}));
    }

    _showSuccess() {
        const successHtml = `
        <div class="success-message">
          <h2>Thank You!</h2>
          <p>${this._escapeHTML(this.intakeData.success_message) || 'Your submission has been received.'}</p>
          ${this.isButtonMode ? '<button type="button" class="modal-close-success-button">Close</button>' : ''}
        </div>
      `;
        if (this.formWrapper) {
            this.formWrapper.innerHTML = successHtml;
            if (this.isButtonMode) {
                const closeButton = this.formWrapper.querySelector('.modal-close-success-button');
                if (closeButton) closeButton.addEventListener('click', this._hideModal.bind(this));
            }
        }
    }

    // --- reCAPTCHA Logic ---
    _initializeRecaptcha(recaptchaContainerElement) {
        if (!recaptchaContainerElement) return;
        const loadRecaptcha = () => this._renderRecaptcha(recaptchaContainerElement);

        if (typeof window.grecaptcha === 'undefined' || typeof window.grecaptcha.render === 'undefined') {
            // If script is not loaded, create it
            if (!document.querySelector('script[src*="recaptcha/api.js"]')) {
                const script = document.createElement('script');
                script.src = 'https://www.google.com/recaptcha/api.js?onload=onRecaptchaLoad&render=explicit';
                script.async = true;
                script.defer = true;
                // The callback function must be on the global window object
                window.onRecaptchaLoad = () => {
                    if (window.grecaptcha && typeof window.grecaptcha.ready === 'function') {
                        window.grecaptcha.ready(loadRecaptcha);
                    }
                };
                document.head.appendChild(script);
            } else {
                // Script is already loading, so just ensure our callback is ready
                window.onRecaptchaLoad = () => {
                    if (window.grecaptcha && typeof window.grecaptcha.ready === 'function') {
                        window.grecaptcha.ready(loadRecaptcha);
                    }
                };
            }
        } else {
            // reCAPTCHA is already available
            window.grecaptcha.ready(loadRecaptcha);
        }
    }

    _renderRecaptcha(recaptchaContainerElement) {
        // Ensure it doesn't render multiple times
        if (recaptchaContainerElement && !recaptchaContainerElement.hasChildNodes()) {
            const siteKey = this.intakeData.recaptcha_site_key || this.getAttribute('recaptcha_site_key');

            if (siteKey) {
                this.recaptchaWidgetId = window.grecaptcha.render(recaptchaContainerElement, {
                    'sitekey': siteKey,
                    'theme': this.getAttribute('recaptcha-theme') || 'light'
                });
            } else {
                console.error('reCAPTCHA site key not provided.');
                recaptchaContainer.innerHTML = `<p class="error-message">reCAPTCHA configuration is missing.</p>`;
            }
        }
    }

    _getRecaptchaToken() {
        return new Promise((resolve, reject) => {
            if (typeof window.grecaptcha !== 'undefined' && this.recaptchaWidgetId !== undefined) {
                const token = window.grecaptcha.getResponse(this.recaptchaWidgetId);
                if (token) {
                    resolve(token);
                } else {
                    // The error will be displayed in the main error container for simplicity
                    reject(new Error('Please complete the reCAPTCHA verification.'));
                }
            } else {
                reject(new Error('reCAPTCHA could not be verified. Please reload and try again.'));
            }
        });
    }

    // --- Styling ---
    _getStyles() {
        return `
      :host {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
        line-height: 1.5; color: #2d3748; display: block;
      }
      .trigger-button {
        display: inline-block; padding: 0.75rem 1.5rem; /* Slightly less padding than submit */
        font-size: 1rem; font-weight: 600; border: none; border-radius: 0.375rem;
        cursor: pointer; transition: background-color 0.2s, opacity 0.2s;
        /* Default colors set in JS, can be overridden by attributes */
      }
      .trigger-button:hover:not(:disabled) { filter: brightness(90%); }
      .intake-wrapper { padding: 1.5rem; max-width: 600px; margin: 1rem auto; border: 1px solid #e2e8f0; border-radius: 0.5rem; background-color: #fff; }
      h2 { margin-top: 0; margin-bottom: 1.5rem; font-size: 1.5rem; font-weight: 600; }
      .form-group { margin-bottom: 1.25rem; }
      .field-label { display: block; font-weight: 500; margin-bottom: 0.5rem; }
      .required { color: #e53e3e; margin-left: 0.25rem; }
      
      .form-input, .form-textarea, .form-select {
        display: block; width: 100%; box-sizing: border-box; padding: 0.75rem;
        border: 1px solid #cbd5e0; border-radius: 0.375rem; font-size: 1rem;
        background-color: white; transition: border-color 0.2s, box-shadow 0.2s;
      }
      .form-input:focus, .form-textarea:focus, .form-select:focus {
        outline: none; border-color: #3182ce; box-shadow: 0 0 0 2px rgba(66, 153, 225, 0.5);
      }
      .form-textarea { resize: vertical; min-height: 100px; }
      
      .form-file-input { font-size: 0.9rem; padding: 0.3rem; }
      /* Modern file input styling */
      .form-file-input::file-selector-button {
        font-weight: 500; border: 1px solid #cbd5e0; padding: 0.5rem 1rem;
        border-radius: 0.25rem; background-color: #f7fafc; cursor: pointer;
        transition: background-color .2s; margin-right: 1rem;
      }
      .form-file-input::file-selector-button:hover { background-color: #edf2f7; }

      .help-text { display: block; font-size: 0.875rem; color: #718096; margin-top: 0.35rem; }
      
      .submit-button {
        display: inline-block; padding: 0.75rem 2rem; background-color: #2c5282; color: white;
        font-size: 1rem; font-weight: 600; border: none; border-radius: 0.375rem;
        cursor: pointer; transition: background-color 0.2s, opacity 0.2s;
      }
      .submit-button:hover:not(:disabled) { background-color: #2a4365; }
      .submit-button:disabled { background-color: #a0aec0; cursor: not-allowed; opacity: 0.7; }
      
      .loading { padding: 1rem; text-align: center; color: #718096; }
      .error, .form-submission-error { color: #c53030; }
      .error { background-color: #fff5f5; border: 1px solid #fc8181; padding: 1rem; border-radius: 0.5rem; }
      .form-submission-error { margin-top: 1rem; font-weight: 500; min-height: 1.2em; text-align: left; }
      .success-message { text-align: center; padding: 2rem; }
      .success-message h2 { color: #2f855a; }
      
      .recaptcha-container { margin: 1.5rem 0; display: flex; justify-content: start; }

      /* Modal Styles */
      .modal-overlay {
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background-color: rgba(0,0,0,0.5); display: flex;
        align-items: center; justify-content: center; z-index: 1000;
        padding: 1rem; box-sizing: border-box;
      }
      .modal-dialog {
        background-color: #fff; border-radius: 0.5rem;
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        width: 100%; max-width: 600px;
        display: flex; flex-direction: column;
        max-height: calc(100vh - 2rem); /* Full height minus padding */
      }
      .modal-header {
        padding: 1rem 1.5rem; border-bottom: 1px solid #e2e8f0;
        display: flex; justify-content: space-between; align-items: center;
      }
      .modal-header .modal-title { margin-bottom: 0; font-size: 1.25rem; }
      .modal-close-button {
        background: none; border: none; font-size: 1.75rem; font-weight: 300;
        color: #718096; cursor: pointer; padding: 0.25rem 0.5rem; line-height: 1;
      }
      .modal-close-button:hover { color: #2d3748; }
      .modal-body {
        padding: 1.5rem; overflow-y: auto;
      }
      .modal-body .loading, .modal-body .error { margin-top: 1rem; }
      .modal-close-success-button { /* Can reuse submit button styles or define new */
        margin-top: 1rem; padding: 0.6rem 1.2rem; background-color: #4A5568; color: white;
        border: none; border-radius: 0.375rem; cursor: pointer;
      }
      .modal-close-success-button:hover { background-color: #2D3748; }
    `;
    }
}

if (!customElements.get('rithom-intake')) {
    customElements.define('rithom-intake', RithomIntake);
}