import { useEffect } from 'react';
import { Minus, Square, X } from '@phosphor-icons/react';
import { usePlatform } from '../../platform';
import styles from './TitleBar.module.css';

/**
 * TitleBar — thin 32px draggable bar shown only on frameless Electron
 * windows. Returns `null` on every other platform so the web and
 * Android builds render as if it didn't exist.
 *
 * The bar itself gets `-webkit-app-region: drag` via CSS; the three
 * action buttons use `no-drag` so clicks go to them instead of the
 * OS's window drag handler. While mounted, sets `.has-window-controls`
 * on <body> so the global stylesheet can pad `#root` to reserve the
 * 32px strip — avoids every top-level layout needing its own offset.
 */
export function TitleBar() {
	const { features, windowControls } = usePlatform();
	const enabled = !!features?.hasWindowControls && !!windowControls;

	useEffect(() => {
		if (!enabled) return;
		document.body.classList.add('has-window-controls');
		return () => {
			document.body.classList.remove('has-window-controls');
		};
	}, [enabled]);

	if (!enabled) return null;

	return (
		<div className={styles.bar}>
			<div className={styles.buttons}>
				<button
					type="button"
					className={styles.button}
					onClick={() => windowControls.minimize()}
					aria-label="Minimize"
					title="Minimize"
				>
					<Minus size={14} weight="bold" />
				</button>
				<button
					type="button"
					className={styles.button}
					onClick={() => windowControls.maximize()}
					aria-label="Maximize"
					title="Maximize"
				>
					<Square size={12} weight="bold" />
				</button>
				<button
					type="button"
					className={`${styles.button} ${styles.closeButton}`}
					onClick={() => windowControls.close()}
					aria-label="Close"
					title="Close"
				>
					<X size={14} weight="bold" />
				</button>
			</div>
		</div>
	);
}
