// Credit: https://usehooks-ts.com/
import { useState } from 'react';
import { copyToClipboard } from '@/lib/clipboard';

export type CopiedValue = string | null;
export type CopyFn = (text: string) => Promise<boolean>;
export type UseClipboardReturn = [CopiedValue, CopyFn];

/**
 * Whether the text was copied, and a way to copy it.
 *
 * The copying itself is `copyToClipboard`, which falls back on an older but
 * still working route when `navigator.clipboard` is missing — as it is on a
 * plain-HTTP host like `http://solarsystem.test`.
 */
export function useClipboard(): UseClipboardReturn {
    const [copiedText, setCopiedText] = useState<CopiedValue>(null);

    const copy: CopyFn = async (text) => {
        const copied = await copyToClipboard(text);

        setCopiedText(copied ? text : null);

        return copied;
    };

    return [copiedText, copy];
}
