import type { SharedProps } from '@/types/inertia';
import { Link, usePage } from '@inertiajs/react';

type Props = {
    className?: string;
};

/**
 * "← {site name}" back link used by guest pages (auth, checkout). Reads
 * branding + landing mode from shared props.
 *
 * Landing-mode behavior:
 *  - enabled  → internal Link to `/` (renders the bundled marketing landing)
 *  - redirect → external anchor to the configured URL (admin's marketing
 *               site at apex domain). Hidden when no valid URL configured.
 *  - login    → hidden entirely. App-only deployment, no marketing surface
 *               to go "back" to.
 */
export default function BackToHomeLink({ className }: Props) {
    const { branding, landingMode } = usePage<SharedProps>().props;
    const name = branding?.site_name || 'AppShot AI';
    const classes =
        className ??
        'mb-6 inline-flex w-fit items-center gap-2 text-xs font-medium text-muted-foreground hover:text-accent';

    if (landingMode.mode === 'login') {
        return null;
    }

    if (landingMode.mode === 'redirect') {
        if (!landingMode.redirectUrl) {
            // Redirect mode but admin hasn't set a URL — nothing sensible to
            // link to. Mirrors the middleware's graceful fallback (which
            // sends visitors to /login in this case).
            return null;
        }
        return (
            <a
                href={landingMode.redirectUrl}
                target="_blank"
                rel="noopener noreferrer"
                className={classes}
            >
                ← {name}
            </a>
        );
    }

    return (
        <Link href="/" className={classes}>
            ← {name}
        </Link>
    );
}
