"use client";

import { useState } from "react";
import { Button } from "./Button";

/*
 * A licence blob is signed public data, not a secret — it is useless on any
 * instance other than the one it names. So it is safe to show inline, and
 * showing it is what stops a blocked download from blocking a paying customer.
 */
export function LicenceDelivery({
    instanceId,
    blob,
    downloadUrl,
}: {
    instanceId: string;
    blob: string;
    downloadUrl: string;
}) {
    const [copied, setCopied] = useState(false);

    async function copy() {
        await navigator.clipboard.writeText(blob);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    }

    const steps = [
        <>
            Open <code className="rounded-sm bg-accent-wash px-1">Settings → Licence</code> on your
            install.
        </>,
        <>Paste the licence into the box and save.</>,
        <>
            The page reports <code className="rounded-sm bg-accent-wash px-1">Valid</code> straight
            away — no restart.
        </>,
    ];

    return (
        <section className="grid gap-3">
            <h2 className="text-xl">Your licence</h2>
            <div className="flex flex-wrap items-center gap-3">
                <a
                    href={downloadUrl}
                    download={`vantage-${instanceId}.lic`}
                    className="inline-flex items-center gap-2 rounded border border-accent bg-accent px-4 py-2.5 text-[0.94rem] font-semibold text-accent-ink"
                >
                    Download licence
                </a>
                <Button variant="line" type="button" onClick={copy}>
                    {copied ? "Copied" : "Copy to clipboard"}
                </Button>
            </div>
            <pre className="overflow-x-auto rounded border border-dashed border-rule bg-panel-2 p-3 font-mono text-[0.72rem] text-ink-2">
                {blob}
            </pre>
            <ol className="grid gap-2">
                {steps.map((body, i) => (
                    <li
                        key={i}
                        className="grid grid-cols-[1.6rem_1fr] gap-3 text-[0.82rem] text-ink-2"
                    >
                        <span className="h-6 rounded-sm border border-rule text-center font-mono text-[0.72rem] leading-6 text-accent">
                            {i + 1}
                        </span>
                        <span>{body}</span>
                    </li>
                ))}
            </ol>
        </section>
    );
}
