import { Head, router, useForm } from "@inertiajs/react";
import {
    Building2,
    Image as ImageIcon,
    Palette,
    RotateCcw,
    Sparkles,
    Trash2,
    Type,
} from "lucide-react";
import { useRef, useState } from "react";
import AppLogoIcon from "@/components/app-logo-icon";
import InputError from "@/components/input-error";
import { BrandingBackgroundGallery } from "@/components/crm/branding-background-gallery";
import { FormField, NativeSelect } from "@/components/crm/native-select";
import { Callout, SectionCard } from "@/components/crm/page-header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
    reset as resetBranding,
    update as updateBranding,
} from "@/routes/branding";
import { apply as applyBackground } from "@/routes/branding/backgrounds";
import { destroy as destroyBrandingImage } from "@/routes/branding/images";
import type { BrandingSettingsProps } from "@/types";

/**
 * A hex colour with a picker beside it, used for both the accent and the
 * sign-in panel's ground so the two are set the same way.
 */
function ColourPicker({
    id,
    label,
    value,
    error,
    hint,
    onChange,
}: {
    id: string;
    label: string;
    value: string;
    error?: string;
    hint?: string;
    onChange: (value: string) => void;
}) {
    return (
        <FormField label={label} htmlFor={id} error={error} hint={hint}>
            <div className="flex items-center gap-2">
                <input
                    id={id}
                    type="color"
                    aria-label={label}
                    value={value}
                    className="h-9 w-12 shrink-0 cursor-pointer rounded-md border border-input bg-transparent p-1"
                    onChange={(event) =>
                        onChange(event.target.value.toLowerCase())
                    }
                />
                <Input
                    value={value}
                    className="font-mono"
                    aria-label={`${label} hex value`}
                    onChange={(event) => onChange(event.target.value)}
                />
            </div>
        </FormField>
    );
}

/**
 * Settings -> Company profile.
 *
 * Everything a solar company changes to make this system theirs: who the
 * company legally is and where it is, the name it runs under, the words on the
 * landing and sign-in screens, the accent colour that reaches the whole
 * interface, and the logo and background image. Nothing here is compiled in,
 * which is what makes the same code sellable to the next client.
 */
export default function CompanyProfileSettings({
    branding,
    defaults,
    states,
}: BrandingSettingsProps) {
    const form = useForm({
        name: branding.name,
        legal_name: branding.legal_name ?? "",
        abn: branding.abn ?? "",
        acn: branding.acn ?? "",
        address_line1: branding.address_line1 ?? "",
        address_line2: branding.address_line2 ?? "",
        suburb: branding.suburb ?? "",
        state: branding.state ?? "",
        postcode: branding.postcode ?? "",
        country: branding.country ?? defaults.country,
        support_email: branding.support_email ?? "",
        support_phone: branding.support_phone ?? "",
        website: branding.website ?? "",
        tagline: branding.tagline,
        headline: branding.headline,
        subheadline: branding.subheadline,
        primary_color: branding.primary_color ?? defaults.primary_color,
        // The staff sign-in screen: its own words, the colour its panel falls
        // back to without a photograph, and the three lines it lists.
        login_eyebrow: branding.login_eyebrow,
        login_headline: branding.login_headline,
        login_tagline: branding.login_tagline,
        login_card_title: branding.login_card_title,
        login_card_description: branding.login_card_description,
        login_footer_note: branding.login_footer_note,
        login_feature_1_title: branding.login_features[0]?.title ?? "",
        login_feature_1_body: branding.login_features[0]?.body ?? "",
        login_feature_2_title: branding.login_features[1]?.title ?? "",
        login_feature_2_body: branding.login_features[1]?.body ?? "",
        login_feature_3_title: branding.login_features[2]?.title ?? "",
        login_feature_3_body: branding.login_features[2]?.body ?? "",
        login_background_color:
            branding.login_background_color ?? defaults.login_background_color,
        logo: null as File | null,
        login_background: null as File | null,
    });

    const [logoName, setLogoName] = useState<string | null>(null);
    const [backgroundName, setBackgroundName] = useState<string | null>(null);
    const logoInput = useRef<HTMLInputElement>(null);
    const backgroundInput = useRef<HTMLInputElement>(null);

    // The panel keeps its built-in artwork — the navy it shipped with, warmed
    // by the accent — until a colour is actually chosen. The preview mirrors
    // that, so it never promises a screen the sign-in page will not paint.
    const loginGlow =
        form.data.login_background_color === defaults.login_background_color
            ? form.data.primary_color
            : form.data.login_background_color;

    const submit = () => {
        // forceFormData because of the two images: Inertia sends a multipart
        // body as soon as one of them is present, and this makes sure of it.
        form.post(updateBranding().url, {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => {
                setLogoName(null);
                setBackgroundName(null);

                if (logoInput.current) {
                    logoInput.current.value = "";
                }

                if (backgroundInput.current) {
                    backgroundInput.current.value = "";
                }
            },
        });
    };

    const upload = (
        field: "logo" | "login_background",
        file: File | null,
        setName: (name: string | null) => void,
    ) => {
        form.setData(field, file);
        setName(file?.name ?? null);
    };

    const removeImage = (slot: "logo" | "login-background") => {
        if (
            !window.confirm(
                "Remove this image? The page it appears on falls back to the plain background.",
            )
        ) {
            return;
        }

        router.delete(destroyBrandingImage({ slot }).url, {
            preserveScroll: true,
        });
    };

    const useExistingBackground = (path: string) => {
        router.post(
            applyBackground().url,
            { path },
            // Keep anything typed but not yet saved in the rest of the form.
            { preserveScroll: true, preserveState: true },
        );
    };

    const resetEverything = () => {
        if (
            !window.confirm(
                "Put every company profile setting back to the defaults, images included?",
            )
        ) {
            return;
        }

        router.delete(resetBranding().url, { preserveScroll: true });
    };

    return (
        <>
            <Head title="Company profile" />

            <Callout
                tone={branding.customised ? "success" : "info"}
                icon={Sparkles}
                title={
                    branding.customised
                        ? `${branding.name} is running under its own profile`
                        : "This installation is still on its defaults"
                }
            >
                {branding.customised
                    ? "These details are this installation’s own, and only the pages a client sees carry them: the sign-in screen, the landing page, the sidebar and the browser tab."
                    : "Set the company name, ABN and address here and the whole system carries them — which is what makes the same codebase fit the next solar company too."}
            </Callout>

            <SectionCard
                title="Company details"
                description="Who this installation belongs to and where the company is, so a customer can be told and a document can carry it."
                icon={Building2}
                tone="solar"
            >
                <div className="grid gap-x-6 gap-y-4 md:grid-cols-2">
                    <FormField
                        label="Company name"
                        htmlFor="name"
                        error={form.errors.name}
                        hint="Sidebar, browser tab and sign-in screen"
                        required
                    >
                        <Input
                            id="name"
                            value={form.data.name}
                            placeholder={defaults.name}
                            onChange={(event) =>
                                form.setData("name", event.target.value)
                            }
                        />
                    </FormField>

                    <FormField
                        label="Legal name"
                        htmlFor="legal_name"
                        error={form.errors.legal_name}
                        hint="The registered entity, if it differs"
                    >
                        <Input
                            id="legal_name"
                            value={form.data.legal_name}
                            placeholder="Southern Cross Solar Pty Ltd"
                            onChange={(event) =>
                                form.setData("legal_name", event.target.value)
                            }
                        />
                    </FormField>

                    <FormField
                        label="ABN"
                        htmlFor="abn"
                        error={form.errors.abn}
                        hint="11 digits"
                    >
                        <Input
                            id="abn"
                            value={form.data.abn}
                            placeholder="12 345 678 901"
                            onChange={(event) =>
                                form.setData("abn", event.target.value)
                            }
                        />
                    </FormField>

                    <FormField
                        label="ACN"
                        htmlFor="acn"
                        error={form.errors.acn}
                        hint="9 digits, if the company has one"
                    >
                        <Input
                            id="acn"
                            value={form.data.acn}
                            placeholder="123 456 789"
                            onChange={(event) =>
                                form.setData("acn", event.target.value)
                            }
                        />
                    </FormField>

                    <FormField
                        label="Street address"
                        htmlFor="address_line1"
                        error={form.errors.address_line1}
                        hint="Where the business is"
                        className="md:col-span-2"
                    >
                        <Input
                            id="address_line1"
                            value={form.data.address_line1}
                            placeholder="1 Example Street"
                            onChange={(event) =>
                                form.setData(
                                    "address_line1",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>

                    <FormField
                        label="Address line 2"
                        htmlFor="address_line2"
                        error={form.errors.address_line2}
                        hint="Suite, level or PO box"
                        className="md:col-span-2"
                    >
                        <Input
                            id="address_line2"
                            value={form.data.address_line2}
                            placeholder="Suite 4"
                            onChange={(event) =>
                                form.setData(
                                    "address_line2",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>

                    <FormField
                        label="Suburb"
                        htmlFor="suburb"
                        error={form.errors.suburb}
                    >
                        <Input
                            id="suburb"
                            value={form.data.suburb}
                            placeholder="Wonthaggi"
                            onChange={(event) =>
                                form.setData("suburb", event.target.value)
                            }
                        />
                    </FormField>

                    <div className="grid grid-cols-2 gap-x-6 gap-y-4">
                        <FormField
                            label="State"
                            htmlFor="state"
                            error={form.errors.state}
                        >
                            <NativeSelect
                                id="state"
                                value={form.data.state}
                                onChange={(event) =>
                                    form.setData("state", event.target.value)
                                }
                            >
                                <option value="">Not set</option>
                                {states.map((state) => (
                                    <option
                                        key={state.value}
                                        value={state.value}
                                    >
                                        {state.value} — {state.label}
                                    </option>
                                ))}
                            </NativeSelect>
                        </FormField>

                        <FormField
                            label="Postcode"
                            htmlFor="postcode"
                            error={form.errors.postcode}
                        >
                            <Input
                                id="postcode"
                                value={form.data.postcode}
                                placeholder="3995"
                                onChange={(event) =>
                                    form.setData("postcode", event.target.value)
                                }
                            />
                        </FormField>
                    </div>

                    <FormField
                        label="Country"
                        htmlFor="country"
                        error={form.errors.country}
                        hint="Only printed when it is not Australia"
                    >
                        <Input
                            id="country"
                            value={form.data.country}
                            placeholder={defaults.country}
                            onChange={(event) =>
                                form.setData("country", event.target.value)
                            }
                        />
                    </FormField>

                    <FormField
                        label="Support email"
                        htmlFor="support_email"
                        error={form.errors.support_email}
                        hint="Shown in the landing page footer"
                    >
                        <Input
                            id="support_email"
                            type="email"
                            value={form.data.support_email}
                            placeholder="support@example.com"
                            onChange={(event) =>
                                form.setData(
                                    "support_email",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>

                    <FormField
                        label="Support phone"
                        htmlFor="support_phone"
                        error={form.errors.support_phone}
                        hint="The number a customer is given"
                    >
                        <Input
                            id="support_phone"
                            value={form.data.support_phone}
                            placeholder="1300 000 000"
                            onChange={(event) =>
                                form.setData(
                                    "support_phone",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>

                    <FormField
                        label="Website"
                        htmlFor="website"
                        error={form.errors.website}
                        hint="Linked from the landing page"
                    >
                        <Input
                            id="website"
                            value={form.data.website}
                            placeholder="https://example.com.au"
                            onChange={(event) =>
                                form.setData("website", event.target.value)
                            }
                        />
                    </FormField>
                </div>
            </SectionCard>

            <SectionCard
                title="Brand and landing page"
                description="The name this system is sold under, the accent colour that reaches the whole interface, and the words a customer reads on the landing page before they sign in."
                icon={Palette}
                tone="info"
            >
                <div className="grid gap-x-6 gap-y-4 md:grid-cols-2">
                    <FormField
                        label="Tagline"
                        htmlFor="tagline"
                        error={form.errors.tagline}
                        hint="One line under the name"
                        className="md:col-span-2"
                    >
                        <Input
                            id="tagline"
                            value={form.data.tagline}
                            placeholder={defaults.tagline}
                            onChange={(event) =>
                                form.setData("tagline", event.target.value)
                            }
                        />
                    </FormField>

                    <FormField
                        label="Landing headline"
                        htmlFor="headline"
                        error={form.errors.headline}
                        hint="The biggest line on the landing page"
                        className="md:col-span-2"
                    >
                        <Input
                            id="headline"
                            value={form.data.headline}
                            placeholder={defaults.headline}
                            onChange={(event) =>
                                form.setData("headline", event.target.value)
                            }
                        />
                    </FormField>

                    <FormField
                        label="Landing supporting line"
                        htmlFor="subheadline"
                        error={form.errors.subheadline}
                        hint="A sentence under the headline"
                        className="md:col-span-2"
                    >
                        <textarea
                            id="subheadline"
                            value={form.data.subheadline}
                            placeholder={defaults.subheadline}
                            rows={3}
                            className="min-h-20 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 dark:bg-input/30"
                            onChange={(event) =>
                                form.setData("subheadline", event.target.value)
                            }
                        />
                    </FormField>

                    <FormField
                        label="Accent colour"
                        htmlFor="primary_color"
                        error={form.errors.primary_color}
                        hint="Used across the whole interface"
                        className="md:col-span-2"
                    >
                        <div className="flex items-center gap-2">
                            <input
                                id="primary_color"
                                type="color"
                                aria-label="Accent colour"
                                value={form.data.primary_color}
                                className="h-9 w-12 shrink-0 cursor-pointer rounded-md border border-input bg-transparent p-1"
                                onChange={(event) =>
                                    form.setData(
                                        "primary_color",
                                        event.target.value.toLowerCase(),
                                    )
                                }
                            />
                            <Input
                                value={form.data.primary_color}
                                className="font-mono"
                                onChange={(event) =>
                                    form.setData(
                                        "primary_color",
                                        event.target.value,
                                    )
                                }
                            />
                        </div>

                        {/* What the colour becomes once the theme derives its
                            tinted background and its readable ink from it. */}
                        <div className="mt-2 flex items-center gap-2 text-xs">
                            <span
                                className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 font-medium text-foreground ring-1 ring-inset"
                                style={{
                                    backgroundColor: `color-mix(in oklab, ${form.data.primary_color} 12%, white)`,
                                    color: `color-mix(in oklab, ${form.data.primary_color} 55%, black)`,
                                    borderColor: form.data.primary_color,
                                }}
                            >
                                <Palette className="size-3" />
                                Accent preview
                            </span>
                            <span
                                className="size-4 rounded-full ring-1 ring-hairline"
                                style={{
                                    backgroundColor: form.data.primary_color,
                                }}
                            />
                        </div>
                    </FormField>
                </div>
            </SectionCard>

            <SectionCard
                title="Sign-in page words"
                description="Everything staff read before they are in: the label beside the logo, the headline on the panel, the card they type into, and the three lines that say what this system does. A blank headline or supporting line falls back to the brand's."
                icon={Type}
                tone="info"
            >
                <div className="grid gap-x-6 gap-y-4 md:grid-cols-2">
                    <FormField
                        label="Label beside the logo"
                        htmlFor="login_eyebrow"
                        error={form.errors.login_eyebrow}
                        hint="Small capitals, under the company name"
                        className="md:col-span-2"
                    >
                        <Input
                            id="login_eyebrow"
                            value={form.data.login_eyebrow}
                            placeholder={defaults.login_eyebrow}
                            onChange={(event) =>
                                form.setData(
                                    "login_eyebrow",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>

                    <FormField
                        label="Panel headline"
                        htmlFor="login_headline"
                        error={form.errors.login_headline}
                        hint="The biggest line on the sign-in panel"
                        className="md:col-span-2"
                    >
                        <Input
                            id="login_headline"
                            value={form.data.login_headline}
                            placeholder={
                                defaults.login_headline || defaults.headline
                            }
                            onChange={(event) =>
                                form.setData(
                                    "login_headline",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>

                    <FormField
                        label="Panel supporting line"
                        htmlFor="login_tagline"
                        error={form.errors.login_tagline}
                        hint="A sentence under the headline"
                        className="md:col-span-2"
                    >
                        <textarea
                            id="login_tagline"
                            value={form.data.login_tagline}
                            placeholder={
                                defaults.login_tagline || defaults.tagline
                            }
                            rows={2}
                            className="min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 dark:bg-input/30"
                            onChange={(event) =>
                                form.setData(
                                    "login_tagline",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>

                    <FormField
                        label="Card heading"
                        htmlFor="login_card_title"
                        error={form.errors.login_card_title}
                        hint="Above the email field"
                    >
                        <Input
                            id="login_card_title"
                            value={form.data.login_card_title}
                            placeholder={defaults.login_card_title}
                            onChange={(event) =>
                                form.setData(
                                    "login_card_title",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>

                    <FormField
                        label="Card sentence"
                        htmlFor="login_card_description"
                        error={form.errors.login_card_description}
                        hint="What to do, under the heading"
                    >
                        <Input
                            id="login_card_description"
                            value={form.data.login_card_description}
                            placeholder={defaults.login_card_description}
                            onChange={(event) =>
                                form.setData(
                                    "login_card_description",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>

                    <FormField
                        label="Line under the card"
                        htmlFor="login_footer_note"
                        error={form.errors.login_footer_note}
                        hint="Shown with the support email, when one is set"
                        className="md:col-span-2"
                    >
                        <Input
                            id="login_footer_note"
                            value={form.data.login_footer_note}
                            placeholder={defaults.login_footer_note}
                            onChange={(event) =>
                                form.setData(
                                    "login_footer_note",
                                    event.target.value,
                                )
                            }
                        />
                    </FormField>
                </div>

                <div className="mt-5 grid gap-3">
                    <div>
                        <p className="text-sm font-medium">
                            What the panel says this system does
                        </p>
                        <p className="text-xs text-muted-foreground">
                            Three lines, in this order. The icons stay; the
                            words are yours.
                        </p>
                    </div>

                    {(
                        [
                            {
                                line: 1,
                                title: "login_feature_1_title",
                                body: "login_feature_1_body",
                            },
                            {
                                line: 2,
                                title: "login_feature_2_title",
                                body: "login_feature_2_body",
                            },
                            {
                                line: 3,
                                title: "login_feature_3_title",
                                body: "login_feature_3_body",
                            },
                        ] as const
                    ).map(({ line, title, body }) => (
                        <div
                            key={line}
                            className="grid gap-2 rounded-xl bg-muted/40 p-3 ring-1 ring-hairline"
                        >
                            <p className="text-[11px] font-medium tracking-[0.12em] text-muted-foreground uppercase">
                                Line {line}
                            </p>
                            <Input
                                aria-label={`Line ${line} heading`}
                                value={form.data[title]}
                                placeholder={
                                    defaults.login_features[line - 1]?.title ??
                                    ""
                                }
                                onChange={(event) =>
                                    form.setData(title, event.target.value)
                                }
                            />
                            <Input
                                aria-label={`Line ${line} sentence`}
                                value={form.data[body]}
                                placeholder={
                                    defaults.login_features[line - 1]?.body ??
                                    ""
                                }
                                onChange={(event) =>
                                    form.setData(body, event.target.value)
                                }
                            />
                            <InputError
                                message={
                                    form.errors[title] ?? form.errors[body]
                                }
                            />
                        </div>
                    ))}
                </div>
            </SectionCard>

            <SectionCard
                title="Sign-in page background"
                description="The photograph behind the staff sign-in screen, and the colour it falls back to when there is no photograph. A landscape photo works best — its edges are darkened with the colour below so the words on top stay readable."
                icon={ImageIcon}
                tone="info"
            >
                <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_18rem]">
                    <div className="grid gap-3">
                        <ColourPicker
                            id="login_background_color"
                            label="Colour without a photograph"
                            value={form.data.login_background_color}
                            error={form.errors.login_background_color}
                            hint="Darkened automatically so white text stays readable."
                            onChange={(value) =>
                                form.setData("login_background_color", value)
                            }
                        />

                        <FormField
                            label="Background image"
                            htmlFor="login_background"
                            error={form.errors.login_background}
                            hint="PNG, JPG or WebP, up to 8 MB · landscape, 1600 × 1000 or larger"
                        >
                            <Input
                                id="login_background"
                                type="file"
                                accept="image/png,image/jpeg,image/webp"
                                ref={backgroundInput}
                                onChange={(event) =>
                                    upload(
                                        "login_background",
                                        event.target.files?.[0] ?? null,
                                        setBackgroundName,
                                    )
                                }
                            />
                        </FormField>

                        {backgroundName ? (
                            <p className="text-xs text-muted-foreground">
                                {backgroundName} will be uploaded when you save.
                            </p>
                        ) : null}

                        {branding.login_background_url ? (
                            <div>
                                <Button
                                    type="button"
                                    variant="outline"
                                    size="sm"
                                    onClick={() =>
                                        removeImage("login-background")
                                    }
                                >
                                    <Trash2 />
                                    Remove the background
                                </Button>
                            </div>
                        ) : null}
                    </div>

                    <div
                        className="relative flex min-h-52 flex-col justify-between overflow-hidden rounded-xl p-4 text-white ring-1 ring-hairline"
                        style={{
                            backgroundColor: `color-mix(in oklab, ${form.data.login_background_color} 30%, #050a12)`,
                        }}
                    >
                        {branding.login_background_url ? (
                            <div
                                className="absolute inset-0 bg-cover bg-center"
                                style={{
                                    backgroundImage: `url(${branding.login_background_url})`,
                                }}
                            />
                        ) : (
                            <div
                                className="absolute inset-0"
                                style={{
                                    backgroundImage: `radial-gradient(115% 78% at 84% -12%, color-mix(in oklab, ${loginGlow} 52%, transparent) 0%, color-mix(in oklab, ${loginGlow} 16%, transparent) 38%, transparent 66%)`,
                                }}
                            />
                        )}
                        <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/35 to-transparent" />

                        <div className="relative flex items-center gap-2">
                            {branding.logo_url ? (
                                <img
                                    src={branding.logo_url}
                                    alt=""
                                    className="size-7 rounded-md object-cover ring-1 ring-white/20"
                                />
                            ) : (
                                <span className="flex size-7 items-center justify-center rounded-md bg-white/10 ring-1 ring-white/20">
                                    <AppLogoIcon className="size-3.5 fill-white" />
                                </span>
                            )}
                            <span className="min-w-0">
                                <span className="block truncate text-xs font-semibold">
                                    {branding.name}
                                </span>
                                <span className="block truncate text-[9px] font-medium tracking-[0.14em] text-white/50 uppercase">
                                    {form.data.login_eyebrow}
                                </span>
                            </span>
                        </div>

                        <div className="relative space-y-1">
                            <p className="text-sm leading-snug font-semibold">
                                {form.data.login_headline || branding.headline}
                            </p>
                            <p className="line-clamp-2 text-[11px] leading-relaxed text-white/60">
                                {form.data.login_tagline || branding.tagline}
                            </p>
                            <p className="pt-1 text-[10px] font-medium tracking-[0.12em] text-white/40 uppercase">
                                {branding.login_background_url
                                    ? "Photograph behind the sign-in panel"
                                    : "This colour, with the panel lights"}
                            </p>
                        </div>
                    </div>
                </div>

                <BrandingBackgroundGallery
                    title="Uploaded backgrounds"
                    description="Every background kept for this profile. Choose one to put it back on the sign-in screen without uploading it again."
                    images={branding.background_images}
                    selectedPath={
                        branding.background_images.find(
                            (image) => image.in_use,
                        )?.path ?? null
                    }
                    onSelect={useExistingBackground}
                    emptyMessage="No backgrounds saved yet. Upload one above and it will stay here for next time."
                />
            </SectionCard>

            <SectionCard
                title="Logo"
                description="Shown beside the company name on the sign-in screen, the landing page and the sidebar."
                icon={Building2}
                tone="slate"
            >
                <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_16rem]">
                    <div className="grid gap-3">
                        <FormField
                            label="Logo image"
                            htmlFor="logo"
                            error={form.errors.logo}
                            hint="A square PNG works best, up to 4 MB"
                        >
                            <Input
                                id="logo"
                                type="file"
                                accept="image/png,image/jpeg,image/webp"
                                ref={logoInput}
                                onChange={(event) =>
                                    upload(
                                        "logo",
                                        event.target.files?.[0] ?? null,
                                        setLogoName,
                                    )
                                }
                            />
                        </FormField>

                        {logoName ? (
                            <p className="text-xs text-muted-foreground">
                                {logoName} will be uploaded when you save.
                            </p>
                        ) : null}

                        {branding.logo_url ? (
                            <div>
                                <Button
                                    type="button"
                                    variant="outline"
                                    size="sm"
                                    onClick={() => removeImage("logo")}
                                >
                                    <Trash2 />
                                    Remove the logo
                                </Button>
                            </div>
                        ) : null}
                    </div>

                    <div className="flex min-h-32 items-center justify-center rounded-xl bg-muted/40 p-4 ring-1 ring-hairline">
                        {branding.logo_url ? (
                            <img
                                src={branding.logo_url}
                                alt={`${branding.name} logo`}
                                className="max-h-20 max-w-full object-contain"
                            />
                        ) : (
                            <p className="text-xs text-muted-foreground">
                                No logo yet — the solar mark is used.
                            </p>
                        )}
                    </div>
                </div>
            </SectionCard>

            {/* One save row for the whole page: every section above is part of
                the same form, so a client changes what they came for and saves
                once. */}
            <div className="flex flex-col-reverse gap-3 border-t border-hairline pt-4 sm:flex-row sm:items-center sm:justify-between">
                <p className="text-xs text-muted-foreground">
                    {form.recentlySuccessful
                        ? "Saved."
                        : "Applies to this installation only."}
                </p>
                <div className="flex flex-wrap items-center gap-2">
                    <Button
                        type="button"
                        variant="outline"
                        onClick={resetEverything}
                        disabled={form.processing || !branding.customised}
                    >
                        <RotateCcw />
                        Reset to defaults
                    </Button>
                    <Button
                        type="button"
                        onClick={submit}
                        disabled={form.processing}
                    >
                        Save company profile
                    </Button>
                </div>
            </div>
        </>
    );
}
