import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
  BlockerFunction, useBeforeUnload, useBlocker, useLocation, useNavigate, useParams, useSearchParams,
} from "react-router-dom";

import {
  Accordion, AccordionDetails, AccordionSummary, Alert, Box, Button, Chip, Divider, IconButton, Paper,
  Skeleton, Stack, Tab, Tabs, Tooltip, Typography,
} from "@mui/material";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import ArrowForwardIcon from "@mui/icons-material/ArrowForward";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import DescriptionOutlinedIcon from "@mui/icons-material/DescriptionOutlined";
import MailOutlineIcon from "@mui/icons-material/MailOutline";
import FolderOutlinedIcon from "@mui/icons-material/FolderOutlined";
import AutoFixHighIcon from "@mui/icons-material/AutoFixHigh";
import ChecklistIcon from "@mui/icons-material/Checklist";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";

import { getApiErrorMessage } from "../api";
import Attachments from "../components/Attachments";
import Correspondence from "../components/Correspondence";
import ApplicationChecklist from "../components/ApplicationChecklist";
import ApplicationCalendarActions from "../components/ApplicationCalendarActions";
import {
  ApplicationAnalysis, ApplicationMatch, ApplicationTimeline,
} from "../components/ApplicationIntelligence";
import {
  ApplicationCoverLetterSection, ApplicationCvSection, ApplicationPackageDraftsSection,
} from "../components/ApplicationAssets";
import { ApplicationInterviewPrep } from "../components/InterviewPrep";
import EditJobDialog from "../components/EditJobDialog";
import { ApplicationStatusSuggestion, ApplicationStrategySnapshot } from "../components/ApplicationWorkflowAssist";
import { PIPELINE_STATUSES, normalizeStatus, statusLabel, statusTone } from "../pipeline";
import { useI18n } from "../i18n/I18nProvider";
import { useConfirm } from "../confirm";
import {
  WORKSPACE_SECTIONS, WorkspaceOverview, WorkspaceSectionKey, applicationWorkspaceApi,
  checklistSystemTranslationToken, workspaceSection,
} from "../applicationWorkspace";

// Phase 5 Milestone 1 — the dedicated Application Workspace.
//
// This is a surface, not a new data store: the overview is one aggregate read, and each section
// reuses the component that already owns that domain (for example Attachments and Correspondence).
// docs/architecture/application-workspace.md.
export default function ApplicationWorkspacePage() {
  return <ApplicationWorkspace />;
}

type ApplicationWorkspaceProps = {
  jobIdOverride?: number;
  sectionOverride?: WorkspaceSectionKey;
  onSectionChange?: (section: WorkspaceSectionKey) => void;
  onClose?: () => void;
  fullPageHref?: string;
};

export function ApplicationWorkspace({
  jobIdOverride,
  sectionOverride,
  onSectionChange,
  onClose,
  fullPageHref,
}: ApplicationWorkspaceProps) {
  const { id } = useParams();
  const jobId = jobIdOverride ?? Number(id);
  const location = useLocation();
  const navigate = useNavigate();
  const { t } = useI18n();
  const { confirm } = useConfirm();
  const [params, setParams] = useSearchParams();
  const section = sectionOverride ?? workspaceSection(params.get("section"));

  const [overview, setOverview] = useState<WorkspaceOverview | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [editOpen, setEditOpen] = useState(false);
  const [coverLetterDirty, setCoverLetterDirty] = useState(false);
  const [packageDraftsDirty, setPackageDraftsDirty] = useState(false);
  const hasUnsavedChanges = coverLetterDirty || packageDraftsDirty;

  const shouldBlock = useCallback<BlockerFunction>(
    ({ currentLocation, nextLocation }) => hasUnsavedChanges && (
      currentLocation.pathname !== nextLocation.pathname || currentLocation.search !== nextLocation.search
    ),
    [hasUnsavedChanges],
  );
  const blocker = useBlocker(shouldBlock);

  useBeforeUnload(useCallback((event) => {
    if (!hasUnsavedChanges) return;
    event.preventDefault();
    event.returnValue = "";
  }, [hasUnsavedChanges]));

  useEffect(() => {
    if (blocker.state !== "blocked") return;
    const blockedNavigation = blocker;
    let active = true;
    void confirm({
      title: t("workspaceUnsavedTitle"),
      message: t("workspaceUnsavedMessage"),
      confirmLabel: t("workspaceDiscardLeave"),
      cancelLabel: t("workspaceKeepEditing"),
      destructive: true,
    }).then((approved) => {
      if (!active) return;
      if (approved) blockedNavigation.proceed();
      else blockedNavigation.reset();
    });
    return () => { active = false; };
  }, [blocker, confirm, t]);

  const load = useCallback(async () => {
    if (!Number.isInteger(jobId) || jobId <= 0) {
      setOverview(null);
      setError(t("workspaceInvalidLink"));
      return;
    }
    try {
      setError(null);
      setOverview(await applicationWorkspaceApi.overview(jobId));
    } catch (err) {
      setError(getApiErrorMessage(err, t("workspaceLoadFailed")));
    }
  }, [jobId, t]);

  useEffect(() => {
    load();
  }, [load]);

  const go = (next: WorkspaceSectionKey) => {
    if (onSectionChange) onSectionChange(next);
    else setParams({ section: next }, { replace: true, state: location.state });
  };
  const close = onClose ?? (() => {
    const state = location.state as { from?: unknown; focusJobId?: unknown } | null;
    const from = state?.from;
    const focusJobId = typeof state?.focusJobId === "number" ? state.focusJobId : undefined;
    navigate(
      typeof from === "string" && from.startsWith("/") && !from.startsWith("//") ? from : "/jobs",
      { replace: true, state: focusJobId ? { focusJobId } : undefined },
    );
  });

  if (error) {
    return (
      <Box sx={{ p: 3 }}>
        <Button startIcon={<ArrowBackIcon />} onClick={close}>{t("workspaceBack")}</Button>
        <Alert severity="error" sx={{ mt: 2 }}>{error}</Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ display: "grid", gap: 2 }}>
      <Paper sx={{ borderRadius: 3, overflow: "hidden" }}>
        <Stack direction="row" alignItems="center" spacing={0.5} sx={{ px: { xs: 1, sm: 2 }, pt: 1.5 }}>
          <Tooltip title={t("workspaceBack")}>
            <IconButton size="small" aria-label={t("workspaceBack")} onClick={close}>
              <ArrowBackIcon fontSize="small" />
            </IconButton>
          </Tooltip>
          <Typography variant="caption" sx={{ fontWeight: 800, letterSpacing: ".08em", textTransform: "uppercase", color: "text.secondary" }}>
            {t("workspace")}
          </Typography>
          {fullPageHref ? (
            <Tooltip title={t("workspaceOpenFull")}>
              <IconButton
                component="a"
                href={fullPageHref}
                target="_blank"
                rel="noopener noreferrer"
                size="small"
                aria-label={t("workspaceOpenFull")}
                sx={{ ml: "auto" }}
              >
                <OpenInNewIcon fontSize="small" />
              </IconButton>
            </Tooltip>
          ) : null}
        </Stack>
        <WorkspaceHeader overview={overview} onEdit={() => setEditOpen(true)} />
        <Tabs
          value={section}
          onChange={(_, value: WorkspaceSectionKey) => go(value)}
          variant="scrollable"
          scrollButtons="auto"
          aria-label={t("workspaceSections")}
          sx={{ px: { xs: 0.5, sm: 1.5 }, borderTop: 1, borderColor: "divider", minHeight: 46 }}
        >
          {WORKSPACE_SECTIONS.map((s) => <Tab key={s.key} value={s.key} label={workspaceSectionLabel(t, s.key)} sx={{ minHeight: 46, fontWeight: 700 }} />)}
        </Tabs>
      </Paper>

      <Box sx={{ display: "grid", gap: 2, minWidth: 0 }}>
        {section === "overview" && jobId > 0 && <ApplicationStatusSuggestion jobId={jobId} onApplied={load} />}
        {section === "overview" && <OverviewSection overview={overview} onGo={go} onReload={load} onEdit={() => setEditOpen(true)} />}
        {section === "analysis" && jobId > 0 && (
          <Stack spacing={2}>
            <ApplicationAnalysis jobId={jobId} />
            <ApplicationMatch jobId={jobId} />
            <ApplicationStrategySnapshot jobId={jobId} />
          </Stack>
        )}
        {section === "interview" && jobId > 0 && <ApplicationInterviewPrep jobId={jobId} />}
        {section === "cv" && jobId > 0 && <ApplicationCvSection jobId={jobId} />}
        {section === "cover-letter" && jobId > 0 && (
          <>
            <ApplicationCoverLetterSection jobId={jobId} onDirtyChange={setCoverLetterDirty} />
            <ApplicationPackageDraftsSection
              jobId={jobId}
              initialApplicationAnswer={overview?.applicationAnswerDraft ?? ""}
              initialRecruiterMessage={overview?.recruiterMessageDraft ?? ""}
              onSaved={load}
              onDirtyChange={setPackageDraftsDirty}
            />
          </>
        )}
      </Box>
      <EditJobDialog
        open={editOpen}
        jobId={jobId > 0 ? jobId : null}
        onClose={() => setEditOpen(false)}
        onSaved={() => { setEditOpen(false); void load(); }}
      />
    </Box>
  );
}
function WorkspaceHeader({ overview, onEdit }: { overview: WorkspaceOverview | null; onEdit: () => void }) {
  const { t } = useI18n();
  if (!overview) return <Paper sx={{ p: 2.5, borderRadius: 3 }}><Skeleton width="45%" height={34} /><Skeleton width="30%" /></Paper>;
  return (
    <Box sx={{ px: { xs: 2, sm: 3 }, pt: 1, pb: 2.5 }}>
      <Stack direction="row" alignItems="flex-start" justifyContent="space-between" flexWrap="wrap" gap={1}>
        <Box>
          <Typography variant="h5" sx={{ fontWeight: 900 }}>{overview.jobTitle}</Typography>
          <Typography color="text.secondary">
            {[overview.company, overview.location, overview.salary].filter(Boolean).join(" · ") || "—"}
          </Typography>
        </Box>
        <Stack direction="row" spacing={1} alignItems="center">
          <Tooltip title={t("workspaceEditApplication")}>
            <IconButton size="small" aria-label={t("workspaceEditApplication")} onClick={onEdit}>
              <EditOutlinedIcon fontSize="small" />
            </IconButton>
          </Tooltip>
          <Chip size="small" label={statusLabel(t, overview.status)} color={statusTone(overview.status)} variant="outlined" />
          {overview.source ? <Chip size="small" label={overview.source.toUpperCase()} variant="outlined" /> : null}
          {overview.jobUrl && (
            <Tooltip title={t("workspaceOpenAdvert")}>
              <IconButton size="small" aria-label={t("workspaceOpenAdvert")} href={overview.jobUrl} target="_blank" rel="noopener noreferrer">
                <OpenInNewIcon fontSize="small" />
              </IconButton>
            </Tooltip>
          )}
        </Stack>
      </Stack>
      <ApplicationProgress status={overview.status} />
    </Box>
  );
}

function ApplicationProgress({ status }: { status: string }) {
  const { t } = useI18n();
  const normalized = normalizeStatus(status);
  const currentOrder = normalized === "Other" ? Number.MAX_SAFE_INTEGER : PIPELINE_STATUSES.indexOf(normalized) + 1;
  const isTerminal = normalized === "Rejected" || normalized === "Ghosted" || normalized === "Withdrawn";
  const stages = isTerminal
    ? [...PIPELINE_STATUSES.filter((stage) => !["Offer", "Rejected", "Ghosted", "Withdrawn"].includes(stage)), normalized]
    : PIPELINE_STATUSES.filter((stage) => !["Rejected", "Ghosted", "Withdrawn"].includes(stage));

  return (
    <Box sx={{ mt: 2.5 }} aria-label={`${t("workspaceProgress")}: ${statusLabel(t, status)}`}>
      <Typography variant="caption" color="text.secondary" sx={{ fontWeight: 800, letterSpacing: ".06em", textTransform: "uppercase" }}>
        {t("workspaceProgress")}
      </Typography>
      <Box sx={{ display: "flex", overflowX: "auto", pt: 1, pb: 0.5 }}>
        {stages.map((stage, index) => {
          const order = PIPELINE_STATUSES.indexOf(stage) + 1;
          const current = stage === normalized;
          const complete = !current && order < currentOrder;
          return (
            <Box key={stage} sx={{ display: "grid", gridTemplateColumns: index ? "minmax(30px, 1fr) auto" : "auto", alignItems: "center", minWidth: index ? 110 : 72, flex: 1 }}>
              {index > 0 && <Box aria-hidden sx={{ height: 2, bgcolor: complete || current ? "primary.main" : "divider" }} />}
              <Stack alignItems="center" spacing={0.5} sx={{ minWidth: 72 }}>
                <Box aria-hidden sx={{ width: 12, height: 12, borderRadius: "50%", border: 2, borderColor: current || complete ? "primary.main" : "divider", bgcolor: complete ? "primary.main" : "background.paper", boxShadow: current ? (theme) => `0 0 0 4px ${theme.palette.primary.main}26` : "none" }} />
                <Typography variant="caption" sx={{ whiteSpace: "nowrap", fontWeight: current ? 800 : 600, color: current ? "text.primary" : "text.secondary" }}>
                  {statusLabel(t, stage)}
                </Typography>
              </Stack>
            </Box>
          );
        })}
      </Box>
    </Box>
  );
}

function OverviewSection({ overview, onGo, onReload, onEdit }: {
  overview: WorkspaceOverview | null;
  onGo: (s: WorkspaceSectionKey) => void;
  onReload: () => void;
  onEdit: () => void;
}) {
  const { language, t } = useI18n();
  const stats = useMemo(() => overview ? [
    { icon: <DescriptionOutlinedIcon fontSize="small" />, label: t("workspaceCv"), value: overview.cv.variantName ?? (overview.cv.hasTailoredCvText ? t("workspaceTailoredText") : t("workspaceNotPrepared")), ok: !!overview.cv.variantId || overview.cv.hasTailoredCvText, go: "cv" as const },
    { icon: <MailOutlineIcon fontSize="small" />, label: t("jobDetailsCoverLetter"), value: overview.hasCoverLetter ? t("workspaceReady") : t("workspaceNotWritten"), ok: overview.hasCoverLetter, go: "cover-letter" as const },
    { icon: <FolderOutlinedIcon fontSize="small" />, label: t("workspaceDocuments"), value: overview.documentCount ? t("workspaceAttachedCount", { count: overview.documentCount }) : t("assetsNone"), ok: overview.documentCount > 0, go: "overview" as const },
    { icon: <AutoFixHighIcon fontSize="small" />, label: t("workspaceAiSuggestions"), value: overview.aiInteractionCount ? t("workspaceSavedCount", { count: overview.aiInteractionCount }) : t("workspaceNoneYet"), ok: overview.aiInteractionCount > 0, go: "analysis" as const },
    { icon: <ChecklistIcon fontSize="small" />, label: t("workspaceChecklist"), value: overview.checklistProgress ? t("workspaceDoneCount", { completed: overview.checklistProgress.completed, total: overview.checklistProgress.total }) : "—", ok: (overview.checklistProgress?.percent ?? 0) === 100, go: "overview" as const },
  ] : [], [overview, t]);

  if (!overview) {
    return <Stack spacing={2}>{[0, 1].map((i) => <Skeleton key={i} variant="rounded" height={120} />)}</Stack>;
  }

  const nextStepToken = checklistSystemTranslationToken(overview.nextStep?.key);
  const nextStepLabel = overview.nextStep
    ? nextStepToken ? t(`checklistItem_${nextStepToken}` as any) : overview.nextStep.label
    : null;
  const nextStepReason = overview.nextStep
    ? nextStepToken ? t(`checklistItem_${nextStepToken}Description` as any) : overview.nextStep.reason
    : null;

  return (
    <Stack spacing={2}>
      {overview.nextStep ? (
        <Paper sx={{ p: 2.5, borderRadius: 3, borderLeft: "4px solid", borderLeftColor: "primary.main" }}>
          <Typography variant="overline" color="text.secondary">{t("workspaceNextAction")}</Typography>
          <Typography variant="h6" sx={{ fontWeight: 800 }}>{nextStepLabel}</Typography>
          <Typography color="text.secondary" sx={{ mb: 1.5 }}>{nextStepReason}</Typography>
          <Button variant="contained" endIcon={<ArrowForwardIcon />}
            onClick={() => overview.nextStep?.section && onGo(overview.nextStep.section as WorkspaceSectionKey)}>
            {nextStepLabel}
          </Button>
        </Paper>
      ) : (
        <Alert severity="success" sx={{ borderRadius: 3 }}>
          {t("workspaceNothingOutstanding")}
        </Alert>
      )}

      <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "repeat(2, minmax(0, 1fr))", lg: "repeat(5, minmax(0, 1fr))" }, gap: 1.5 }}>
        {stats.map((s) => (
          <Paper key={s.label} variant="outlined" role="button" tabIndex={0}
            onClick={() => onGo(s.go)}
            onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onGo(s.go); } }}
            sx={{ p: 1.5, borderRadius: 3, cursor: "pointer", "&:focus-visible": { boxShadow: 3 } }}>
            <Stack direction="row" spacing={0.75} alignItems="center" sx={{ color: s.ok ? "success.main" : "text.disabled" }}>
              {s.icon}
              <Typography variant="caption" sx={{ fontWeight: 700 }}>{s.label}</Typography>
            </Stack>
            <Typography variant="body2" sx={{ mt: 0.5, fontWeight: 600 }}>{s.value}</Typography>
          </Paper>
        ))}
      </Box>

      <Paper sx={{ p: 2, borderRadius: 3 }}>
        <Stack direction="row" alignItems="center" justifyContent="space-between">
          <Typography variant="subtitle2" sx={{ fontWeight: 800 }}>{t("workspaceRecentActivity")}</Typography>
          <Button size="small" onClick={onReload}>{t("workspaceRefresh")}</Button>
        </Stack>
        <Divider sx={{ my: 1 }} />
        {overview.recentActivity.length === 0 ? (
          <Typography variant="body2" color="text.secondary">{t("workspaceNoActivity")}</Typography>
        ) : (
          <Stack spacing={0.75}>
            {overview.recentActivity.map((a, i) => (
              <Stack key={i} direction="row" spacing={1} justifyContent="space-between">
                <Typography variant="body2"><strong>{a.type}</strong>{a.detail ? ` — ${a.detail}` : ""}</Typography>
                <Typography variant="caption" color="text.secondary">{new Date(a.at).toLocaleDateString(language === "nb" ? "nb-NO" : "en")}</Typography>
              </Stack>
            ))}
          </Stack>
        )}
      </Paper>

      <OverviewDetails jobId={overview.id} overview={overview} onReload={onReload} onEdit={onEdit} />
    </Stack>
  );
}

function OverviewDetails({ jobId, overview, onReload, onEdit }: { jobId: number; overview: WorkspaceOverview; onReload: () => void; onEdit: () => void }) {
  const { t } = useI18n();
  const panels = [
    { id: "details", title: t("workspaceJobDetails"), content: <JobDetailsSection overview={overview} onEdit={onEdit} /> },
    { id: "tasks", title: t("workspaceChecklist"), content: <ApplicationChecklist jobId={jobId} onChanged={onReload} /> },
    { id: "calendar", title: t("calendarTitle"), content: <ApplicationCalendarActions jobId={jobId} followUpAt={overview.followUpAt} deadline={overview.deadline} /> },
    { id: "timeline", title: t("workspaceActivityHistory"), content: <ApplicationTimeline jobId={jobId} /> },
    { id: "documents", title: t("workspaceDocuments"), content: <Attachments jobId={jobId} /> },
    { id: "communication", title: t("workspaceCommunication"), content: <Correspondence jobId={jobId} jobContext={{ companyName: overview.company, jobTitle: overview.jobTitle }} /> },
  ];
  return (
    <Box>
      {panels.map((panel) => (
        <Accordion key={panel.id} disableGutters elevation={0} sx={{ border: 1, borderColor: "divider", "&:not(:last-child)": { borderBottom: 0 }, "&:before": { display: "none" } }}>
          <AccordionSummary expandIcon={<ExpandMoreIcon />} aria-controls={`${panel.id}-content`} id={`${panel.id}-header`}>
            <Typography sx={{ fontWeight: 750 }}>{panel.title}</Typography>
          </AccordionSummary>
          <AccordionDetails id={`${panel.id}-content`} sx={{ px: { xs: 1, sm: 2 }, pb: 2 }}>{panel.content}</AccordionDetails>
        </Accordion>
      ))}
    </Box>
  );
}

function workspaceSectionLabel(t: (key: any) => string, section: WorkspaceSectionKey): string {
  const keys: Record<WorkspaceSectionKey, any> = {
    overview: "workspaceOverview",
    analysis: "workspaceAnalysis",
    cv: "workspaceCv",
    "cover-letter": "workspaceCoverLetter",
    interview: "workspaceInterviewPrep",
  };
  return t(keys[section]);
}

function JobDetailsSection({ overview, onEdit }: { overview: WorkspaceOverview | null; onEdit: () => void }) {
  const { language, t } = useI18n();
  if (!overview) return <Skeleton variant="rounded" height={200} />;
  const rows: [string, string][] = [
    [t("company"), overview.company ?? "—"],
    [t("location"), overview.location ?? "—"],
    [t("workspaceCountry"), overview.countryCode ?? "—"],
    [t("workspaceSource"), overview.source ?? "—"],
    [t("jobDetailsSalary"), overview.salary ?? "—"],
    [t("addJobModalStatus"), statusLabel(t, overview.status)],
    [t("workspaceDiscovered"), overview.savedAt ? new Date(overview.savedAt).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : "—"],
    [t("workspaceApplied"), overview.dateApplied ? new Date(overview.dateApplied).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : "—"],
    [t("jobDetailsDeadline"), overview.deadline ? new Date(overview.deadline).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : "—"],
    [t("intelligenceCategoryFollowUp"), overview.followUpAt ? new Date(overview.followUpAt).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : t("workspaceNotScheduled")],
    [t("workspaceNextAction"), overview.nextAction ?? "—"],
  ];
  return (
    <Stack spacing={2}>
      <Paper sx={{ p: 2.5, borderRadius: 3 }}>
        <Stack direction="row" alignItems="center" justifyContent="space-between" gap={1} sx={{ mb: 1.5 }}>
          <Typography variant="subtitle1" sx={{ fontWeight: 800 }}>{t("workspaceApplicationInfo")}</Typography>
          <Button size="small" startIcon={<EditOutlinedIcon />} onClick={onEdit}>{t("workspaceEdit")}</Button>
        </Stack>
        <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "repeat(2, minmax(0, 1fr))", lg: "repeat(4, minmax(0, 1fr))" }, gap: 1.5 }}>
          {rows.map(([k, v]) => (
            <Box key={k} sx={{ minWidth: 0 }}>
              <Typography variant="caption" color="text.secondary" sx={{ fontWeight: 700 }}>{k}</Typography>
              <Typography variant="body2" sx={{ overflowWrap: "anywhere" }}>{v}</Typography>
            </Box>
          ))}
        </Box>
        {overview.tags.length > 0 ? (
          <Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.75, mt: 2 }}>
            {overview.tags.map((tag) => <Chip key={tag} size="small" label={tag} />)}
          </Box>
        ) : null}
        {overview.notes ? (
          <Box sx={{ mt: 2 }}>
            <Typography variant="caption" color="text.secondary" sx={{ fontWeight: 700 }}>{t("workspaceNotes")}</Typography>
            <Typography variant="body2" sx={{ mt: 0.5, whiteSpace: "pre-wrap", overflowWrap: "anywhere" }}>{overview.notes}</Typography>
          </Box>
        ) : null}
      </Paper>

      <Paper sx={{ p: { xs: 2, sm: 2.5 }, borderRadius: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 800, mb: 1.5 }}>{t("workspaceJobDescription")}</Typography>
        {!overview.hasJobDescription ? (
          <Alert severity="warning" sx={{ borderRadius: 2 }} action={<Button color="inherit" size="small" onClick={onEdit}>{t("workspaceAddAdvert")}</Button>}>
            {t("workspaceNoJobDescription")}
          </Alert>
        ) : (
          <Stack spacing={2.5}>
            {overview.translatedDescription ? (
              <Box>
                <Typography variant="overline" color="text.secondary">{t("workspaceTranslatedAdvert")}</Typography>
                <Typography sx={{ mt: 0.5, whiteSpace: "pre-wrap", overflowWrap: "anywhere", lineHeight: 1.7 }}>{overview.translatedDescription}</Typography>
              </Box>
            ) : null}
            {overview.description ? (
              <Box>
                {overview.translatedDescription ? <Typography variant="overline" color="text.secondary">{t("workspaceOriginalAdvert")}{overview.descriptionLanguage ? ` · ${overview.descriptionLanguage.toUpperCase()}` : ""}</Typography> : null}
                <Typography sx={{ mt: 0.5, whiteSpace: "pre-wrap", overflowWrap: "anywhere", lineHeight: 1.7 }}>{overview.description}</Typography>
              </Box>
            ) : null}
          </Stack>
        )}
      </Paper>
    </Stack>
  );
}
