'use client';

/**
 * Edição detalhada de página/tela do projeto (tipologia website vs aplicação React).
 * Extraído de `app/(dashboard)/projetos/[id]/software/paginas/[paginaId]/page.tsx`.
 * TASK-APR-026 — labels tipológicos (Telas vs Páginas).
 */

import { ArrowLeft, RotateCw, Save } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Button, Space, Tabs, Input, Form, Checkbox, Empty, Alert, Typography, Select, Result, Tooltip } from 'antd';
import { message } from '@/lib/feedback/message';
import { notifyApiError } from '@/lib/feedback/notifyApiError';
import PageWrapper from '@/components/layouts/PageWrapper';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import { useMobilePageActionBarRegistration } from '@/components/layouts/PageShellOptions';
import { FormActions } from '@/components/form';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useMutationCache } from '@/hooks/useMutationCache';
import { useIsMobile } from '@/hooks/useIsMobile';
import { queryKeys } from '@/lib/cache/queryKeys';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { formatDate } from '@/lib/utils/export';
import type { PaginaWebsite } from '@/types/projeto';
import type { PaginatedResponse, Projeto } from '@/types';
import { resolvePaginasTipologiaCopy } from '@/features/projetos/lib/resolveAplicacaoReactTipologiaCopy';
import {
    STATUS_OPCOES,
    TIPO_OPCOES,
    PRIORIDADE_OPCOES,
    ETAPA_OPCOES,
    AMBIENTE_OPCOES,
} from './constants';

const { TextArea } = Input;
const { Text } = Typography;

const PROJETOS_LIST_PATH = '/projetos';

export interface ProjetoSoftwarePaginaDetalheScreenProps {
    projetoId: string;
    paginaId: string;
}

export function ProjetoSoftwarePaginaDetalheScreen({
    projetoId,
    paginaId,
}: ProjetoSoftwarePaginaDetalheScreenProps) {
    const router = useRouter();
    /** Sticky «Salvar» + campos full-width em xs (TASK-APR-048 / AR-OP-017). */
    const isMobileLayout = useIsMobile();
    useMobilePageActionBarRegistration(isMobileLayout);
    const projetoIdSafe = projetoId.trim();
    const paginaIdSafe = paginaId.trim();
    const fetchEnabled =
        Boolean(projetoIdSafe) && Boolean(paginaIdSafe) && paginaIdSafe !== 'nova';

    const { data: projetoResponse } = useQueryCache<Projeto | { projeto?: Projeto }>({
        queryKey: queryKeys.projetos.detail(projetoIdSafe),
        endpoint: API_ENDPOINTS.projetos.show(projetoIdSafe),
        enabled: Boolean(projetoIdSafe),
        staleTime: 1 * 60 * 1000,
    });
    const projeto =
        projetoResponse && typeof projetoResponse === 'object' && 'projeto' in projetoResponse
            ? (projetoResponse as { projeto?: Projeto }).projeto
            : (projetoResponse as Projeto | undefined);
    const tipCopy = resolvePaginasTipologiaCopy(projeto?.categoria_projeto?.codigo);

    const {
        data: pagina,
        isLoading,
        isError,
        isFetched,
        error: queryError,
        refetch,
    } = useQueryCache<PaginaWebsite>({
        queryKey: queryKeys.projetos.pagina(projetoIdSafe, paginaIdSafe),
        endpoint: API_ENDPOINTS.projetos.paginas.show(projetoIdSafe, paginaIdSafe),
        enabled: fetchEnabled,
        staleTime: 1 * 60 * 1000,
        gcTime: 5 * 60 * 1000,
    });

    const errStatus = (queryError as { response?: { status?: number } } | null)?.response?.status;
    const queryErr =
        queryError instanceof Error ? queryError : queryError ? new Error(String(queryError)) : null;

    const { data: usuariosData } = useQueryCache<PaginatedResponse<{ id: number; nome: string }>>({
        queryKey: queryKeys.usuariosCatalog.listWithParams({ per_page: 200 }),
        endpoint: API_ENDPOINTS.usuarios.index,
        params: { per_page: 200, page: 1 },
        staleTime: 5 * 60 * 1000,
    });
    const usuarios = usuariosData?.data ?? [];

    const [formVisaoGeral] = Form.useForm();
    const [formConteudo] = Form.useForm();
    const [formSeo] = Form.useForm();
    const [formDesign] = Form.useForm();
    const [formChecklistDev] = Form.useForm();
    const [formChecklistQA] = Form.useForm();
    const [formChecklistPub] = Form.useForm();

    const updateMutation = useMutationCache({
        endpoint: API_ENDPOINTS.projetos.paginas.update(projetoIdSafe, paginaIdSafe),
        method: 'PUT',
        invalidateQueries: [
            queryKeys.projetos.pagina(projetoIdSafe, paginaIdSafe),
            queryKeys.projetos.paginas(projetoIdSafe),
        ],
        onSuccess: () => {
            message.success('Alterações salvas.');
            refetch();
        },
        onError: (error) => notifyApiError(error, 'Erro ao salvar página. Tente novamente.', 'paginas'),
    });

    useEffect(() => {
        if (!pagina) return;
        formVisaoGeral.setFieldsValue({
            titulo: pagina.titulo ?? '',
            slug: pagina.slug ?? '',
            tipo: pagina.tipo,
            status: pagina.status,
            prioridade: pagina.prioridade ?? undefined,
            etapa_atual: pagina.etapa_atual ?? undefined,
            data_prevista: pagina.data_prevista?.slice(0, 10) ?? '',
            data_inicio: pagina.data_inicio?.slice(0, 10) ?? '',
            data_entrega: pagina.data_entrega?.slice(0, 10) ?? '',
            tags: pagina.tags ?? [],
            responsavel_atual_id: pagina.responsavel_atual_id ?? pagina.responsavel_atual?.id ?? undefined,
            conteudo_id: pagina.responsaveis?.conteudo_id ?? pagina.responsaveis?.conteudo?.id ?? undefined,
            design_id: pagina.responsaveis?.design_id ?? pagina.responsaveis?.design?.id ?? undefined,
            dev_id: pagina.responsaveis?.dev_id ?? pagina.responsaveis?.dev?.id ?? undefined,
            seo_id: pagina.responsaveis?.seo_id ?? pagina.responsaveis?.seo?.id ?? undefined,
            qa_id: pagina.responsaveis?.qa_id ?? pagina.responsaveis?.qa?.id ?? undefined,
        });
        formConteudo.setFieldsValue({
            link_conteudo: pagina.link_conteudo ?? '',
            conteudo: pagina.conteudo ?? '',
            conteudo_ok: pagina.checklist?.conteudo_ok ?? false,
        });
        formSeo.setFieldsValue({
            title: pagina.seo?.title ?? '',
            meta_description: pagina.seo?.meta_description ?? '',
            noindex: pagina.seo?.noindex ?? false,
            canonical: pagina.seo?.canonical ?? '',
            seo_ok: pagina.checklist?.seo_ok ?? false,
        });
        formDesign.setFieldsValue({
            link_figma: pagina.link_figma ?? '',
            design_ok: pagina.checklist?.design_ok ?? false,
        });
        formChecklistDev.setFieldsValue({ dev_ok: pagina.checklist?.dev_ok ?? false });
        formChecklistQA.setFieldsValue({ qa_ok: pagina.checklist?.qa_ok ?? false });
        formChecklistPub.setFieldsValue({
            publicado_ok: pagina.checklist?.publicado_ok ?? false,
            data_publicada: pagina.data_publicada?.slice(0, 10) ?? '',
            ambiente: pagina.ambiente ?? undefined,
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps -- sync form when pagina loads; form refs are stable
    }, [pagina]);

    const listaPaginasPath = `/projetos/${projetoIdSafe}/software/paginas`;

    const pagBreadcrumb = (title: string) => [
        { title: 'PROJETO', path: `/projetos/${projetoIdSafe}` },
        { title: tipCopy.titleSection, path: listaPaginasPath },
        { title },
    ];

    if (!projetoIdSafe || !paginaIdSafe) {
        return (
            <PageWrapper
                breadcrumbItems={[
                    { title: 'Projetos', path: PROJETOS_LIST_PATH },
                    { title: tipCopy.titleSection },
                ]}
            >
                <Alert
                    message="Identificador inválido"
                    description="Projeto ou item ausente na rota."
                    type="error"
                    showIcon
                    action={
                        <Button type="primary" size="small" onClick={() => router.push(PROJETOS_LIST_PATH)}>
                            Voltar à lista de projetos
                        </Button>
                    }
                />
            </PageWrapper>
        );
    }

    if (paginaIdSafe === 'nova') {
        return (
            <ProjetoLayout
                projetoId={projetoIdSafe}
                pageTitle={tipCopy.novaLabel}
                titleSection={tipCopy.titleSection}
                pageIcon="file-alt"
                breadcrumbItems={pagBreadcrumb('Nova')}
            >
                <ContentCard>
                    <Alert
                        type="info"
                        showIcon
                        message={`Criação — ${tipCopy.titleSection}`}
                        description={`Use o fluxo de criação na lista de ${tipCopy.titleSection.toLowerCase()}, se aplicável.`}
                    />
                    <Button style={{ marginTop: 16 }} onClick={() => router.push(listaPaginasPath)}>
                        Voltar à lista
                    </Button>
                </ContentCard>
            </ProjetoLayout>
        );
    }

    if (isLoading && !pagina) {
        return (
            <ProjetoLayout
                projetoId={projetoIdSafe}
                pageTitle="Carregando…"
                titleSection={tipCopy.titleSection}
                pageIcon="file-alt"
                breadcrumbItems={pagBreadcrumb('Detalhe')}
            >
                {null}
            </ProjetoLayout>
        );
    }

    if (isError) {
        const is404 = errStatus === 404;
        return (
            <ProjetoLayout
                projetoId={projetoIdSafe}
                pageTitle={is404 ? 'Não encontrado' : 'Erro'}
                titleSection={tipCopy.titleSection}
                pageIcon="file-alt"
                breadcrumbItems={pagBreadcrumb(is404 ? 'Não encontrado' : 'Erro')}
            >
                <ContentCard>
                    <Result
                        status={is404 ? '404' : 'error'}
                        title={
                            is404
                                ? tipCopy.notFoundTitle
                                : `Não foi possível carregar ${tipCopy.titleSection.toLowerCase()}`
                        }
                        subTitle={
                            queryErr?.message ??
                            (is404
                                ? 'O registro não existe ou você não tem permissão para vê-lo.'
                                : 'Tente novamente em instantes.')
                        }
                        extra={
                            <Space wrap>
                                {!is404 ? (
                                    <Button type="primary" onClick={() => void refetch()}>
                                        Tentar novamente
                                    </Button>
                                ) : null}
                                <Button onClick={() => router.push(listaPaginasPath)}>Voltar à lista</Button>
                            </Space>
                        }
                    />
                </ContentCard>
            </ProjetoLayout>
        );
    }

    if (isFetched && !pagina) {
        return (
            <ProjetoLayout
                projetoId={projetoIdSafe}
                pageTitle="Não encontrado"
                titleSection={tipCopy.titleSection}
                pageIcon="file-alt"
                breadcrumbItems={pagBreadcrumb('Não encontrado')}
            >
                <ContentCard>
                    <Result
                        status="404"
                        title={tipCopy.notFoundTitle}
                        subTitle="A resposta veio vazia."
                        extra={
                            <Button type="primary" onClick={() => router.push(listaPaginasPath)}>
                                Voltar à lista
                            </Button>
                        }
                    />
                </ContentCard>
            </ProjetoLayout>
        );
    }

    if (!pagina) {
        return null;
    }

    const tipoLabel = TIPO_OPCOES.find((o) => o.value === pagina.tipo)?.label ?? pagina.tipo;
    const statusLabel = STATUS_OPCOES.find((o) => o.value === pagina.status)?.label ?? pagina.status;
    const fieldWidth = (desktopPx: number) => (isMobileLayout ? '100%' : desktopPx);
    const saveActions = (
        <FormActions sticky={isMobileLayout}>
            <Button
                type="primary"
                htmlType="submit"
                icon={<Save />}
                loading={updateMutation.isPending}
                block={isMobileLayout}
                size={isMobileLayout ? 'large' : 'middle'}
                data-testid="pagina-detalhe-salvar"
            >
                Salvar
            </Button>
        </FormActions>
    );

    const tabItems = [
        {
            key: 'visao-geral',
            label: 'Visão Geral',
            children: (
                <ContentCard title="Dados gerais">
                    <Form
                        form={formVisaoGeral}
                        layout="vertical"
                        onFinish={(values) =>
                            updateMutation.mutate({
                                ...pagina,
                                titulo: values.titulo,
                                slug: values.slug,
                                tipo: values.tipo,
                                status: values.status,
                                prioridade: values.prioridade || null,
                                etapa_atual: values.etapa_atual || null,
                                data_prevista: values.data_prevista || null,
                                data_inicio: values.data_inicio || null,
                                data_entrega: values.data_entrega || null,
                                tags: values.tags?.length ? values.tags : null,
                                responsavel_atual_id: values.responsavel_atual_id ?? null,
                                responsaveis: {
                                    ...pagina.responsaveis,
                                    conteudo_id: values.conteudo_id ?? null,
                                    design_id: values.design_id ?? null,
                                    dev_id: values.dev_id ?? null,
                                    seo_id: values.seo_id ?? null,
                                    qa_id: values.qa_id ?? null,
                                },
                            })
                        }
                    >
                        <Form.Item name="titulo" label="Título" rules={[{ required: true }]}>
                            <Input placeholder="Título da página" />
                        </Form.Item>
                        <Form.Item name="slug" label="Slug / URL" rules={[{ required: true }]}>
                            <Input placeholder="url-amigavel" />
                        </Form.Item>
                        <Space wrap style={{ width: '100%' }}>
                            <Form.Item
                                name="tipo"
                                label="Tipo"
                                rules={[{ required: true }]}
                                style={{ marginBottom: 0, minWidth: isMobileLayout ? '100%' : 160, flex: isMobileLayout ? '1 1 100%' : undefined }}
                            >
                                <Select placeholder="Tipo" options={[...TIPO_OPCOES]} style={{ width: fieldWidth(160) }} />
                            </Form.Item>
                            <Form.Item
                                name="status"
                                label="Status"
                                rules={[{ required: true }]}
                                style={{ marginBottom: 0, minWidth: isMobileLayout ? '100%' : 160, flex: isMobileLayout ? '1 1 100%' : undefined }}
                            >
                                <Select placeholder="Status" options={[...STATUS_OPCOES]} style={{ width: fieldWidth(160) }} />
                            </Form.Item>
                            <Form.Item
                                name="prioridade"
                                label="Prioridade"
                                style={{ marginBottom: 0, minWidth: isMobileLayout ? '100%' : 120, flex: isMobileLayout ? '1 1 100%' : undefined }}
                            >
                                <Select allowClear placeholder="Prioridade" options={PRIORIDADE_OPCOES} style={{ width: fieldWidth(120) }} />
                            </Form.Item>
                            <Form.Item
                                name="etapa_atual"
                                label="Etapa atual (dono da bola)"
                                style={{ marginBottom: 0, minWidth: isMobileLayout ? '100%' : 180, flex: isMobileLayout ? '1 1 100%' : undefined }}
                            >
                                <Select allowClear placeholder="Etapa" options={ETAPA_OPCOES} style={{ width: fieldWidth(180) }} />
                            </Form.Item>
                        </Space>
                        <Space wrap style={{ width: '100%' }}>
                            <Form.Item name="data_prevista" label="Data prevista" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Input type="date" style={{ width: fieldWidth(160) }} />
                            </Form.Item>
                            <Form.Item name="data_inicio" label="Data início" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Input type="date" style={{ width: fieldWidth(160) }} />
                            </Form.Item>
                            <Form.Item name="data_entrega" label="Data entrega" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Input type="date" style={{ width: fieldWidth(160) }} />
                            </Form.Item>
                        </Space>
                        <Form.Item name="tags" label="Tags">
                            <Select
                                mode="tags"
                                placeholder="Ex: SEO pendente, LGPD, banner"
                                tokenSeparators={[',']}
                                style={{ width: '100%' }}
                            />
                        </Form.Item>
                        <Form.Item name="responsavel_atual_id" label="Responsável atual (dono da bola)">
                            <Select
                                allowClear
                                placeholder="Selecione"
                                options={usuarios.map((u) => ({ value: u.id, label: u.nome }))}
                                showSearch
                                optionFilterProp="label"
                                style={{ width: fieldWidth(260) }}
                            />
                        </Form.Item>
                        <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                            Responsáveis por disciplina
                        </Text>
                        <Space wrap style={{ width: '100%' }}>
                            <Form.Item name="conteudo_id" label="Conteúdo (copy)" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Select
                                    allowClear
                                    placeholder="Conteúdo"
                                    options={usuarios.map((u) => ({ value: u.id, label: u.nome }))}
                                    showSearch
                                    optionFilterProp="label"
                                    style={{ width: fieldWidth(180) }}
                                />
                            </Form.Item>
                            <Form.Item name="design_id" label="Design" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Select
                                    allowClear
                                    placeholder="Design"
                                    options={usuarios.map((u) => ({ value: u.id, label: u.nome }))}
                                    showSearch
                                    optionFilterProp="label"
                                    style={{ width: fieldWidth(180) }}
                                />
                            </Form.Item>
                            <Form.Item name="dev_id" label="Dev" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Select
                                    allowClear
                                    placeholder="Dev"
                                    options={usuarios.map((u) => ({ value: u.id, label: u.nome }))}
                                    showSearch
                                    optionFilterProp="label"
                                    style={{ width: fieldWidth(180) }}
                                />
                            </Form.Item>
                            <Form.Item name="seo_id" label="SEO" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Select
                                    allowClear
                                    placeholder="SEO"
                                    options={usuarios.map((u) => ({ value: u.id, label: u.nome }))}
                                    showSearch
                                    optionFilterProp="label"
                                    style={{ width: fieldWidth(180) }}
                                />
                            </Form.Item>
                            <Form.Item name="qa_id" label="QA" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Select
                                    allowClear
                                    placeholder="QA"
                                    options={usuarios.map((u) => ({ value: u.id, label: u.nome }))}
                                    showSearch
                                    optionFilterProp="label"
                                    style={{ width: fieldWidth(180) }}
                                />
                            </Form.Item>
                        </Space>
                        <div style={{ marginTop: 16, paddingBottom: isMobileLayout ? 88 : 0 }}>{saveActions}</div>
                    </Form>
                </ContentCard>
            ),
        },
        {
            key: 'conteudo',
            label: 'Conteúdo',
            children: (
                <ContentCard title="Conteúdo e referência">
                    <Form
                        form={formConteudo}
                        layout="vertical"
                        onFinish={(values) =>
                            updateMutation.mutate({
                                ...pagina,
                                link_conteudo: values.link_conteudo || null,
                                conteudo: values.conteudo || null,
                                checklist: { ...pagina.checklist, conteudo_ok: values.conteudo_ok ?? false },
                            })
                        }
                    >
                        <Form.Item name="link_conteudo" label="Fonte do conteúdo (Figma/Notion/Doc)">
                            <Input placeholder="https://..." />
                        </Form.Item>
                        <Form.Item name="conteudo" label="Conteúdo ou referência">
                            <TextArea rows={8} placeholder="Blocos, Markdown ou referência..." />
                        </Form.Item>
                        <Form.Item name="conteudo_ok" valuePropName="checked">
                            <Checkbox>Conteúdo aprovado / pronto</Checkbox>
                        </Form.Item>
                        <div style={{ paddingBottom: isMobileLayout ? 88 : 0 }}>{saveActions}</div>
                    </Form>
                </ContentCard>
            ),
        },
        {
            key: 'seo',
            label: 'SEO',
            children: (
                <ContentCard title="SEO">
                    <Form
                        form={formSeo}
                        layout="vertical"
                        onFinish={(values) =>
                            updateMutation.mutate({
                                ...pagina,
                                seo: {
                                    ...pagina.seo,
                                    title: values.title || null,
                                    meta_description: values.meta_description || null,
                                    noindex: values.noindex ?? false,
                                    canonical: values.canonical || null,
                                },
                                checklist: { ...pagina.checklist, seo_ok: values.seo_ok ?? false },
                            })
                        }
                    >
                        <Form.Item name="title" label="Title (50–60 caracteres)">
                            <Input placeholder="Título da página para SEO" maxLength={70} showCount />
                        </Form.Item>
                        <Form.Item name="meta_description" label="Meta description (140–160 caracteres)">
                            <TextArea rows={2} placeholder="Descrição para resultados de busca" maxLength={170} showCount />
                        </Form.Item>
                        <Form.Item name="canonical" label="URL canônica">
                            <Input placeholder="https://..." />
                        </Form.Item>
                        <Form.Item name="noindex" valuePropName="checked">
                            <Checkbox>Noindex (não indexar)</Checkbox>
                        </Form.Item>
                        <Form.Item name="seo_ok" valuePropName="checked">
                            <Checkbox>SEO revisado / aprovado</Checkbox>
                        </Form.Item>
                        <div style={{ paddingBottom: isMobileLayout ? 88 : 0 }}>{saveActions}</div>
                    </Form>
                </ContentCard>
            ),
        },
        {
            key: 'design',
            label: 'Design',
            children: (
                <ContentCard title="Design">
                    <Form
                        form={formDesign}
                        layout="vertical"
                        onFinish={(values) =>
                            updateMutation.mutate({
                                ...pagina,
                                link_figma: values.link_figma || null,
                                checklist: { ...pagina.checklist, design_ok: values.design_ok ?? false },
                            })
                        }
                    >
                        <Form.Item name="link_figma" label="Link do Figma">
                            <Input placeholder="https://figma.com/..." />
                        </Form.Item>
                        <Form.Item name="design_ok" valuePropName="checked">
                            <Checkbox>Layout/design aprovado</Checkbox>
                        </Form.Item>
                        <div style={{ paddingBottom: isMobileLayout ? 88 : 0 }}>{saveActions}</div>
                    </Form>
                    <Text type="secondary">
                        Checklist de componentes e aprovação de layout podem ser expandidos depois.
                    </Text>
                </ContentCard>
            ),
        },
        {
            key: 'desenvolvimento',
            label: 'Desenvolvimento',
            children: (
                <ContentCard title="Desenvolvimento">
                    <Form
                        form={formChecklistDev}
                        layout="vertical"
                        onFinish={(values) =>
                            updateMutation.mutate({
                                ...pagina,
                                checklist: { ...pagina.checklist, dev_ok: values.dev_ok },
                            })
                        }
                    >
                        <Form.Item name="dev_ok" valuePropName="checked">
                            <Checkbox>
                                Implementação pronta para QA (responsivo, performance, acessibilidade, componentes
                                reutilizáveis, integração CMS/API)
                            </Checkbox>
                        </Form.Item>
                        <div style={{ paddingBottom: isMobileLayout ? 88 : 0 }}>{saveActions}</div>
                    </Form>
                    <Alert
                        type="info"
                        showIcon
                        message="Checklist: responsivo, performance (Lighthouse), acessibilidade, componentes reutilizáveis, integração CMS/API."
                        style={{ marginTop: 16 }}
                    />
                </ContentCard>
            ),
        },
        {
            key: 'qa',
            label: 'QA & Homologação',
            children: (
                <ContentCard title="QA e homologação">
                    <Form
                        form={formChecklistQA}
                        layout="vertical"
                        onFinish={(values) =>
                            updateMutation.mutate({
                                ...pagina,
                                checklist: { ...pagina.checklist, qa_ok: values.qa_ok },
                            })
                        }
                    >
                        <Form.Item name="qa_ok" valuePropName="checked">
                            <Checkbox>QA concluído (funcional, responsivo, navegador, links, formulários)</Checkbox>
                        </Form.Item>
                        <div style={{ paddingBottom: isMobileLayout ? 88 : 0 }}>{saveActions}</div>
                    </Form>
                    <Text type="secondary">Checklist de testes e evidências.</Text>
                </ContentCard>
            ),
        },
        {
            key: 'publicacao',
            label: 'Publicação',
            children: (
                <ContentCard title="Publicação">
                    <Form
                        form={formChecklistPub}
                        layout="vertical"
                        onFinish={(values) =>
                            updateMutation.mutate({
                                ...pagina,
                                checklist: { ...pagina.checklist, publicado_ok: values.publicado_ok },
                                data_publicada: values.data_publicada || null,
                                ambiente: values.ambiente || null,
                            })
                        }
                    >
                        <Form.Item name="publicado_ok" valuePropName="checked">
                            <Checkbox>
                                Publicado (redirect, sitemap/robots, analytics, cache/CDN conferidos)
                            </Checkbox>
                        </Form.Item>
                        <Space wrap style={{ width: '100%' }}>
                            <Form.Item name="data_publicada" label="Data publicada" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Input type="date" style={{ width: fieldWidth(160) }} />
                            </Form.Item>
                            <Form.Item name="ambiente" label="Ambiente" style={{ marginBottom: 0, flex: isMobileLayout ? '1 1 100%' : undefined }}>
                                <Select
                                    allowClear
                                    placeholder="Ambiente"
                                    options={AMBIENTE_OPCOES}
                                    style={{ width: fieldWidth(140) }}
                                />
                            </Form.Item>
                        </Space>
                        <div style={{ paddingBottom: isMobileLayout ? 88 : 0 }}>{saveActions}</div>
                    </Form>
                    <Alert
                        type="info"
                        showIcon
                        message="Checklist final: redirect (se alterou slug), sitemap/robots, analytics, cache/CDN."
                        style={{ marginTop: 16 }}
                    />
                </ContentCard>
            ),
        },
        {
            key: 'historico',
            label: 'Histórico / Versões',
            children: (
                <ContentCard title="Histórico de alterações">
                    {Array.isArray(pagina.historico) && pagina.historico.length > 0 ? (
                        <ul style={{ paddingLeft: 20 }}>
                            {(pagina.historico as { id?: number; created_at?: string; descricao?: string }[]).map(
                                (h, i) => (
                                    <li key={h.id ?? i}>
                                        {h.created_at && formatDate(h.created_at)} —{' '}
                                        {String((h as { descricao?: string }).descricao ?? 'Alteração')}
                                    </li>
                                )
                            )}
                        </ul>
                    ) : (
                        <Empty description="Nenhum registro de histórico ainda." />
                    )}
                </ContentCard>
            ),
        },
    ];

    return (
        <ProjetoLayout
            projetoId={projetoIdSafe}
            pageTitle={pagina.titulo ?? pagina.slug ?? tipCopy.detalheFallbackTitle}
            titleSection={tipCopy.titleSection}
            pageIcon="file-alt"
            breadcrumbItems={pagBreadcrumb(pagina.titulo ?? pagina.slug ?? 'Detalhe')}
            headerAction={
                <Space wrap size={8} align="center">
                    <Tooltip title={tipCopy.voltarListaTooltip}>
                        <span style={{ display: 'inline-block' }}>
                            <Button icon={<ArrowLeft />} onClick={() => router.push(listaPaginasPath)}>
                                Voltar
                            </Button>
                        </span>
                    </Tooltip>
                    <Tooltip title="Recarregar dados">
                        <span style={{ display: 'inline-block' }}>
                            <Button icon={<RotateCw />} onClick={() => refetch()}>
                                Atualizar
                            </Button>
                        </span>
                    </Tooltip>
                </Space>
            }
        >
            <p className="ant-typography" style={{ marginBottom: 16, color: '#666' }}>
                {tipoLabel} · {statusLabel}
            </p>

            <ContentCard>
                <Tabs defaultActiveKey="visao-geral" items={tabItems} />
            </ContentCard>
        </ProjetoLayout>
    );
}
