export const ADDRESS_LINE_MAX_LENGTH = 40;

export function isAddressLineWithinLimit(line, maxLen = ADDRESS_LINE_MAX_LENGTH) {
    if (line == null || line === '') return true;
    return line.length <= maxLen;
}

/** Step-0 gate: line1 required; lines 1–3 each <= maxLen */
export function isRegisterAddressValid(data, maxLen = ADDRESS_LINE_MAX_LENGTH) {
    return (
        data.address1 !== '' &&
        isAddressLineWithinLimit(data.address1, maxLen) &&
        isAddressLineWithinLimit(data.address2, maxLen) &&
        isAddressLineWithinLimit(data.address3, maxLen)
    );
}

/**
 * Split a comma-separated address into up to 3 lines, each <= maxLen chars.
 * Packs at comma boundaries where possible.
 */
export function splitAddressIntoLines(address, maxLen = ADDRESS_LINE_MAX_LENGTH) {
    const empty = { address1: '', address2: '', address3: '' };
    if (address == null || address === '') return empty;

    const trimmed = address.trim();
    if (trimmed.length <= maxLen) {
        return { address1: trimmed, address2: '', address3: '' };
    }

    const segments = trimmed.split(',').map((s) => s.trim()).filter(Boolean);
    const lines = [];
    let current = '';

    const pushCurrent = () => {
        if (current) {
            lines.push(current);
            current = '';
        }
    };

    for (const segment of segments) {
        const candidate = current ? `${current}, ${segment}` : segment;
        if (candidate.length <= maxLen) {
            current = candidate;
        } else if (segment.length <= maxLen) {
            pushCurrent();
            current = segment;
        } else {
            pushCurrent();
            let remaining = segment;
            while (remaining.length > maxLen) {
                lines.push(remaining.slice(0, maxLen));
                remaining = remaining.slice(maxLen);
            }
            current = remaining;
        }
        if (lines.length >= 3) break;
    }
    pushCurrent();

    return {
        address1: lines[0] ?? '',
        address2: lines[1] ?? '',
        address3: lines[2] ?? '',
    };
}
