/* global jQuery */
( function ( $ ) {
	'use strict';

	var PREFIX = 'aamo_collapse_';

	function slugify( str ) {
		return str.replace( /[^a-z0-9]+/gi, '_' ).toLowerCase().replace( /^_+|_+$/g, '' );
	}

	function getKey( $panel, $title ) {
		var id = $panel.attr( 'id' );
		return PREFIX + ( id || slugify( $title.text() ) );
	}

	function readState( key ) {
		try { return localStorage.getItem( key ) === '1'; } catch ( e ) { return false; }
	}

	function saveState( key, collapsed ) {
		try { localStorage.setItem( key, collapsed ? '1' : '0' ); } catch ( e ) {}
	}

	function setChevron( $chevron, collapsed ) {
		$chevron
			.toggleClass( 'dashicons-arrow-up-alt2',  ! collapsed )
			.toggleClass( 'dashicons-arrow-down-alt2',  collapsed );
	}

	$( function () {
		$( '.aamo-settings-panel' ).each( function () {
			var $panel  = $( this );
			var $title  = $panel.children( '.aamo-settings-panel-title' );
			if ( ! $title.length ) { return; }

			var key      = getKey( $panel, $title );
			var $chevron = $( '<span class="aamo-collapse-chevron dashicons" aria-hidden="true"></span>' );
			$title.append( $chevron );

			var collapsed = readState( key );
			if ( collapsed ) { $panel.addClass( 'aamo-panel-collapsed' ); }
			setChevron( $chevron, collapsed );

			$title.on( 'click', function () {
				var now = $panel.toggleClass( 'aamo-panel-collapsed' ).hasClass( 'aamo-panel-collapsed' );
				setChevron( $chevron, now );
				saveState( key, now );
			} );
		} );
	} );

} )( jQuery );
