import { ExternalLink } from 'lucide-react';
import { FloatingField } from '@/Components/Proto/UI/FloatingField';

// Normalize a user-entered website into an absolute href. Users routinely type a bare
// domain ("acme.co.id") with no scheme; without one the browser would treat it as a
// relative path. Prepend https:// when no http(s) scheme is present so the open button
// always navigates to the real site.
function toHref(raw) {
    const v = (raw ?? '').trim();
    if (!v) return null;

    return /^https?:\/\//i.test(v) ? v : `https://${v}`;
}

/**
 * WebsiteField — the Company website input plus a click-to-open button. The button sits
 * INSIDE the field, anchored to its right edge (input suffix), and opens the entered site
 * in a new tab. It only appears once a value is present, so empty forms stay clean.
 */
export function WebsiteField({ value, onChange, label = 'Website' }) {
    const href = toHref(value);

    return (
        <div className="relative">
            {/* pr-9 keeps the typed URL clear of the suffix button. */}
            <FloatingField type="url" label={label} value={value} onChange={onChange} className={href ? '[&_input]:pr-9' : undefined} />
            {href && (
                <a
                    href={href}
                    target="_blank"
                    rel="noopener noreferrer"
                    title={`Buka ${value}`}
                    aria-label={`Buka ${value}`}
                    className="absolute right-1.5 top-[22px] grid size-7 -translate-y-1/2 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-primary"
                >
                    <ExternalLink className="size-3.5" aria-hidden="true" />
                </a>
            )}
        </div>
    );
}
