import React, { useEffect, useState } from "react";
import AutoFixHighIcon from "@mui/icons-material/AutoFixHigh";
import { Alert, Box, Button, MenuItem, Paper, Stack, TextField, Typography } from "@mui/material";
import { getApiErrorMessage } from "../../api";
import { useAccountPlan } from "../../accountPlan";
import { AI_ACTIONS, cvBuilderApi } from "../../cvBuilder";
import { useToast } from "../../toast";
import ProFeatureNotice from "../ProFeatureNotice";
import { useI18n } from "../../i18n/I18nProvider";
type Props = {
sectionName: string;
text: string;
context?: string;
documentLanguage?: string | null;
onApply: (suggestion: string) => void;
};
const SECTION_ACTIONS = new Set(["improve", "professional", "shorten", "grammar", "impact", "bullets"]);
export default function AiSectionAssistant({ sectionName, text, context, documentLanguage, onApply }: Props) {
const { t } = useI18n();
const { toast } = useToast();
const { canUseAi } = useAccountPlan();
const [open, setOpen] = useState(false);
const [action, setAction] = useState("improve");
const [suggestion, setSuggestion] = useState("");
const [busy, setBusy] = useState(false);
const normalizedLanguage = documentLanguage === "no" || documentLanguage === "nb" ? "nb-NO" : documentLanguage ?? "en";
const [targetLanguage, setTargetLanguage] = useState(normalizedLanguage);
useEffect(() => setTargetLanguage(normalizedLanguage), [normalizedLanguage]);
const run = async () => {
if (!text.trim() || !canUseAi) return;
setBusy(true);
try {
const response = await cvBuilderApi.aiAssist({
action,
text,
language: targetLanguage,
context: [`Section: ${sectionName}. Preserve facts and do not invent achievements.`, context].filter(Boolean).join("\n"),
});
setSuggestion(response.result);
} catch (error) {
toast(getApiErrorMessage(error, t("cvAiFailed")), "error");
} finally {
setBusy(false);
}
};
if (!open) {
return (
} disabled={!text.trim()} onClick={() => setOpen(true)}>
{t("cvAiSuggestions")}
);
}
if (!canUseAi) {
return (
{t("cvAiProBody")}
);
}
return (
setAction(event.target.value)} sx={{ minWidth: 190 }}>
{AI_ACTIONS.filter((item) => SECTION_ACTIONS.has(item.key)).map((item) => )}
setTargetLanguage(event.target.value)} sx={{ minWidth: 150 }}>
{suggestion && <>
{t("cvAiCurrent")}
{text}
setSuggestion(event.target.value)} />
{t("cvAiCheckFacts")}
>}
);
}
type Translate = ReturnType["t"];
function actionLabel(key: string, fallback: string, t: Translate) {
const labels: Record = {
improve: t("cvAiImprove"), professional: t("cvAiProfessional"), shorten: t("cvAiShorten"),
grammar: t("cvAiGrammar"), impact: t("cvAiImpact"), bullets: t("cvAiBullets"),
};
return labels[key] ?? fallback;
}