/**
 * Copyfend — admin panel navigation + DMCA generator (no build step).
 * Switches sections client-side and remembers the active one across saves.
 */
( function () {
	'use strict';

	var KEY = 'cshield_active_view';

	function show( view ) {
		document.querySelectorAll( '.cs-nav a[data-view]' ).forEach( function ( a ) {
			a.classList.toggle( 'active', a.getAttribute( 'data-view' ) === view );
		} );

		document.querySelectorAll( '.cs-view' ).forEach( function ( s ) {
			s.classList.remove( 'active' );
		} );

		var el = document.getElementById( 'view-' + view );
		if ( ! el ) {
			el = document.getElementById( 'view-dashboard' );
			view = 'dashboard';
		}
		if ( el ) {
			el.classList.add( 'active' );
		}

		var savebar = document.querySelector( '.cs-savebar' );
		if ( savebar ) {
			savebar.style.display = ( 'dashboard' === view ) ? 'none' : '';
		}

		try {
			window.sessionStorage.setItem( KEY, view );
		} catch ( e ) {}
	}

	document.addEventListener( 'click', function ( e ) {
		var nav = e.target.closest ? e.target.closest( '.cs-nav a[data-view]' ) : null;
		if ( nav ) {
			e.preventDefault();
			show( nav.getAttribute( 'data-view' ) );
			window.scrollTo( { top: 0, behavior: 'smooth' } );
			return;
		}
		var jump = e.target.closest ? e.target.closest( '[data-goto]' ) : null;
		if ( jump ) {
			e.preventDefault();
			show( jump.getAttribute( 'data-goto' ) );
			window.scrollTo( { top: 0, behavior: 'smooth' } );
		}
	} );

	/* ---- One-shot banners: strip their URL params so a reload doesn't re-show them ---- */
	if ( window.history && window.history.replaceState && window.URL ) {
		var cleanUrl = new URL( window.location.href );
		if ( cleanUrl.searchParams.has( 'cshield-profile' ) || cleanUrl.searchParams.has( 'settings-updated' ) ) {
			cleanUrl.searchParams.delete( 'cshield-profile' );
			cleanUrl.searchParams.delete( 'settings-updated' );
			window.history.replaceState( null, '', cleanUrl.toString() );
		}
	}

	var savedBanner = document.querySelector( '.cs-saved' );
	if ( savedBanner ) {
		window.setTimeout( function () {
			savedBanner.style.transition = 'opacity .4s';
			savedBanner.style.opacity = '0';
			window.setTimeout( function () {
				savedBanner.remove();
			}, 450 );
		}, 2600 );
	}

	document.querySelectorAll( '.cs-dismiss' ).forEach( function ( btn ) {
		btn.addEventListener( 'click', function () {
			var card = btn.closest( '.cs-card' );
			if ( card ) {
				card.remove();
			}
		} );
	} );

	/* ---- Re-open the profile chooser from the discreet dashboard link ---- */
	var changeProfile = document.getElementById( 'cs-change-profile' );
	if ( changeProfile ) {
		changeProfile.addEventListener( 'click', function ( e ) {
			e.preventDefault();
			var welcome = document.getElementById( 'cs-welcome' );
			if ( welcome ) {
				welcome.classList.remove( 'cs-hide' );
				window.scrollTo( { top: 0, behavior: 'smooth' } );
			}
		} );
	}

	/* ---- "Enable all / Disable all" links: toggle every switch in the same card ---- */
	document.querySelectorAll( '.cs-enable-all' ).forEach( function ( link ) {
		var card = link.closest( '.cs-card' );
		if ( ! card ) {
			return;
		}

		function boxes() {
			return Array.prototype.slice.call( card.querySelectorAll( 'input[type="checkbox"]:not(:disabled)' ) );
		}
		function allOn() {
			return boxes().every( function ( box ) {
				return box.checked;
			} );
		}
		function sync() {
			link.textContent = allOn() ? link.getAttribute( 'data-disable' ) : link.getAttribute( 'data-enable' );
		}

		link.addEventListener( 'click', function ( e ) {
			e.preventDefault();
			var target = ! allOn();
			boxes().forEach( function ( box ) {
				box.checked = target;
			} );
			sync();
		} );
		card.addEventListener( 'change', sync );
		sync();
	} );

	/* ---- Copy-shortcode buttons (Content Locker how-to) ---- */
	document.querySelectorAll( '.cs-copy-sc' ).forEach( function ( btn ) {
		btn.addEventListener( 'click', function () {
			var ta = document.getElementById( btn.getAttribute( 'data-target' ) );
			if ( ! ta ) {
				return;
			}
			if ( navigator.clipboard ) {
				navigator.clipboard.writeText( ta.value );
			} else {
				ta.select();
				document.execCommand( 'copy' );
			}
			var label = btn.textContent;
			btn.textContent = btn.getAttribute( 'data-copied' ) || label;
			window.setTimeout( function () {
				btn.textContent = label;
			}, 1500 );
		} );
	} );

	/* ---- DMCA takedown notice generator (client-side, no server) ---- */
	( function () {
		var gen = document.getElementById( 'cs-dmca-generate' );
		if ( ! gen ) {
			return;
		}
		var box  = document.getElementById( 'cs-dmca' );
		var out  = document.getElementById( 'cs-dmca-output' );

		function val( sel ) {
			var el = document.querySelector( sel );
			return el ? el.value.trim() : '';
		}

		function build() {
			var site      = box ? ( box.getAttribute( 'data-site' ) || '' ) : '';
			var holder    = val( '[name="cshield_settings[copyright_holder]"]' ) || site;
			var email     = val( '[name="cshield_settings[copyright_email]"]' );
			var infringing = val( '#cs-dmca-infringing' );
			var original  = val( '#cs-dmca-original' );
			var work      = val( '#cs-dmca-work' );
			var date      = new Date().toLocaleDateString();

			return [
				'To Whom It May Concern,', '',
				'I am submitting this notice under the Digital Millennium Copyright Act (DMCA) to report copyright infringement.', '',
				'1. Original copyrighted work, owned by me:',
				'   ' + ( original || '[your original URL]' ),
				work ? ( '   ' + work ) : '', '',
				'2. Infringing material I request to be removed:',
				'   ' + ( infringing || '[infringing URL]' ), '',
				'3. My contact information:',
				'   Name:  ' + ( holder || '[your name]' ),
				'   Email: ' + ( email || '[your email]' ), '',
				'4. I have a good faith belief that the use described above is not authorized by the copyright owner, its agent, or the law.', '',
				'5. I state, under penalty of perjury, that the information in this notice is accurate, and that I am the copyright owner or am authorized to act on the owner\'s behalf.', '',
				'Signed: ' + ( holder || '[your name]' ),
				'Date:   ' + date
			].join( '\n' );
		}

		gen.addEventListener( 'click', function () {
			if ( out ) {
				out.value = build();
			}
		} );

		var copy = document.getElementById( 'cs-dmca-copy' );
		if ( copy ) {
			copy.addEventListener( 'click', function () {
				if ( ! out || ! out.value ) {
					return;
				}
				out.select();
				if ( navigator.clipboard ) {
					navigator.clipboard.writeText( out.value );
				} else {
					document.execCommand( 'copy' );
				}
			} );
		}

		var dl = document.getElementById( 'cs-dmca-download' );
		if ( dl ) {
			dl.addEventListener( 'click', function () {
				if ( ! out || ! out.value ) {
					return;
				}
				var blob = new Blob( [ out.value ], { type: 'text/plain' } );
				var a    = document.createElement( 'a' );
				a.href     = URL.createObjectURL( blob );
				a.download = 'dmca-takedown-notice.txt';
				document.body.appendChild( a );
				a.click();
				document.body.removeChild( a );
			} );
		}

		// Enter inside generator fields builds the notice instead of saving settings.
		[ '#cs-dmca-infringing', '#cs-dmca-original', '#cs-dmca-work' ].forEach( function ( sel ) {
			var el = document.querySelector( sel );
			if ( el ) {
				el.addEventListener( 'keydown', function ( ev ) {
					if ( 'Enter' === ev.key ) {
						ev.preventDefault();
						if ( out ) {
							out.value = build();
						}
					}
				} );
			}
		} );
	} )();

	var initial = 'dashboard';
	try {
		initial = window.sessionStorage.getItem( KEY ) || 'dashboard';
	} catch ( e ) {}
	show( initial );
} )();
