/** Small custom UI kit (no wp.components). Styled in assets/css/admin-app.css under the `rt-` prefix. */
import { h, Fragment, useEffect, useRef, useId } from '../react';
import { __ } from '../api';

const cx = (...a) => a.filter(Boolean).join(' ');

export function Spinner() {
    return <span className="rt-spinner" role="status" aria-label={__('Loading')} />;
}

export function Button({ variant = 'secondary', size, busy, danger, href, className, children, ...rest }) {
    const cls = cx('rt-btn', `rt-btn--${variant}`, size === 'sm' && 'rt-btn--sm', danger && 'rt-btn--danger', busy && 'is-busy', className);
    if (href) return <a className={cls} href={href} {...rest}>{children}</a>;
    return (
        <button type="button" className={cls} disabled={rest.disabled || busy} {...rest}>
            {busy && <Spinner />}{children}
        </button>
    );
}

export function Pill({ status, children }) {
    return <span className={cx('rt-pill', `rt-pill--${status}`)}>{children}</span>;
}

export function Card({ title, actions, children, flush }) {
    return (
        <section className="rt-card">
            {(title || actions) && (
                <header className="rt-card__head">{title && <h2>{title}</h2>}{actions}</header>
            )}
            <div className={cx('rt-card__body', flush && 'is-flush')}>{children}</div>
        </section>
    );
}

export function Notice({ type = 'info', onDismiss, children }) {
    return (
        <div className={cx('rt-notice', `rt-notice--${type}`)} role={type === 'error' ? 'alert' : 'status'}>
            <span>{children}</span>
            {onDismiss && <button type="button" className="rt-notice__x" onClick={onDismiss} aria-label={__('Dismiss')}>×</button>}
        </div>
    );
}

export function Toggle({ label, help, checked, onChange }) {
    const id = useId();
    return (
        <div className="rt-field rt-field--toggle">
            <button type="button" id={id} role="switch" aria-checked={checked} className={cx('rt-switch', checked && 'is-on')} onClick={() => onChange(!checked)}>
                <span className="rt-switch__knob" />
            </button>
            <label htmlFor={id}>
                <span className="rt-field__label">{label}</span>
                {help && <span className="rt-field__help">{help}</span>}
            </label>
        </div>
    );
}

export function NumberField({ label, help, value, min, max, step, onChange }) {
    const id = useId();
    const bad = value === '' || value < min || value > max;
    return (
        <div className="rt-field">
            <label htmlFor={id} className="rt-field__label">{label}</label>
            <input id={id} className={cx('rt-input', bad && 'is-invalid')} type="number" min={min} max={max} step={step || 1} value={value}
                   onChange={(e) => onChange(e.target.value === '' ? '' : Number(e.target.value))} />
            <span className="rt-field__help">{help || ''}{bad ? ` ${__('Allowed range:')} ${min}–${max}` : ''}</span>
        </div>
    );
}

export function SearchBox({ value, onChange, placeholder }) {
    return (
        <div className="rt-search">
            <input type="search" className="rt-input" value={value} placeholder={placeholder} aria-label={placeholder} onChange={(e) => onChange(e.target.value)} />
        </div>
    );
}

export function Pagination({ page, pages, onChange }) {
    if (pages <= 1) return null;
    return (
        <nav className="rt-pager" aria-label={__('Pagination')}>
            <Button size="sm" disabled={page <= 1} onClick={() => onChange(page - 1)}>{__('Previous')}</Button>
            <span>{page} / {pages}</span>
            <Button size="sm" disabled={page >= pages} onClick={() => onChange(page + 1)}>{__('Next')}</Button>
        </nav>
    );
}

export function Modal({ title, onClose, children }) {
    const ref = useRef(null);
    useEffect(() => {
        const prev = document.activeElement;
        const node = ref.current;
        const focusables = () => node.querySelectorAll('button, [href], input, [tabindex]:not([tabindex="-1"])');
        (focusables()[0] || node).focus();
        const onKey = (e) => {
            if (e.key === 'Escape') { e.stopPropagation(); onClose(); }
            if (e.key === 'Tab') {
                const f = focusables(); if (!f.length) return;
                const first = f[0], last = f[f.length - 1];
                if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
                else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
            }
        };
        document.addEventListener('keydown', onKey);
        return () => { document.removeEventListener('keydown', onKey); if (prev && prev.focus) prev.focus(); };
    }, []);
    return (
        <div className="rt-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
            <div className="rt-modal" role="dialog" aria-modal="true" aria-label={title} tabIndex="-1" ref={ref}>
                <h2>{title}</h2>
                {children}
            </div>
        </div>
    );
}

export function ConfirmModal({ title, message, confirmLabel, danger, busy, onConfirm, onCancel }) {
    return (
        <Modal title={title} onClose={onCancel}>
            <p>{message}</p>
            <div className="rt-modal__actions">
                <Button variant="ghost" onClick={onCancel} disabled={busy}>{__('Cancel')}</Button>
                <Button variant="primary" danger={danger} busy={busy} onClick={onConfirm}>{confirmLabel}</Button>
            </div>
        </Modal>
    );
}

export function StatTile({ label, value, hint, tone }) {
    return (
        <div className={cx('rt-tile', tone && `rt-tile--${tone}`)}>
            <span className="rt-tile__label">{label}</span>
            <strong className="rt-tile__value">{value}</strong>
            {hint && <span className="rt-tile__hint">{hint}</span>}
        </div>
    );
}

/** Dependency-free SVG bar chart. data: [{label, value}] */
export function BarChart({ data, height = 160, ariaLabel }) {
    const max = Math.max(1, ...data.map((d) => d.value));
    const w = 100 / data.length;
    return (
        <figure className="rt-chart" role="img" aria-label={ariaLabel}>
            <svg viewBox={`0 0 100 ${height / 4}`} preserveAspectRatio="none" width="100%" height={height}>
                {[0.25, 0.5, 0.75, 1].map((f) => (
                    <line key={f} x1="0" x2="100" y1={(height / 4) * (1 - f)} y2={(height / 4) * (1 - f)} className="rt-chart__grid" vectorEffect="non-scaling-stroke" />
                ))}
                {data.map((d, i) => {
                    const bh = (d.value / max) * (height / 4 - 2);
                    return (
                        <rect key={i} x={i * w + w * 0.18} width={w * 0.64} y={height / 4 - bh} height={bh} rx="0.6" className="rt-chart__bar">
                            <title>{`${d.label}: ${d.value}`}</title>
                        </rect>
                    );
                })}
            </svg>
            <div className="rt-chart__axis">
                {data.map((d, i) => (i % 3 === 0 || i === data.length - 1) ? <span key={i} style={{ left: `${i * w + w / 2}%` }}>{d.label}</span> : null)}
            </div>
            <figcaption className="rt-chart__max">{__('Peak')}: {max}</figcaption>
        </figure>
    );
}

export { Fragment };
