/*************************************************
 * 作者信息 Tab —— 创作者基本信息（独立文件，window.NRAuthorTab）
 * 两 tab：信息（7 个结构化字段）/ 提炼结果（AI 作者背景）
 * （形象照已拆到左侧菜单「我的照片」独立页，多形象 ≤5 张）
 * 保存后 LLM 提炼「作者背景」，每次生成自动注入；填写不强制，
 * 但未填写时本页是左侧菜单第一项、进来先到这里提醒一次（可自由点走）
 * 表单用受控 useState（不用 antd Form：本栈下 rc-field-form 有
 * 切字段清空前值的 bug，受控写法最稳）
 *************************************************/
const { useState: AS, useEffect: AE } = React;
const {
	Button: ABt, Input: AIp, Card: ACd, message: AMg, Empty: AEm, Spin: ASp,
	Popconfirm: APc, Space: ASP, Tabs: ATabs,
} = antd;

//7 个字段：key / 标签 / 占位 / 类型（text=单行 area=多行）/ 最大长度
const AUTHOR_FIELDS = [
	{ k: "name", label: "称呼（内容里的「我」是谁）", ph: "如：小王 / 阿珍 / 10年工长老张", type: "text", max: 30, required: true },
	{ k: "role", label: "身份角色（选填）", ph: "如：装修工作室主理人 / 宝妈好物分享者", type: "text", max: 60 },
	{ k: "industry", label: "行业领域（选填）", ph: "如：装修 / 餐饮 / 美业", type: "text", max: 30 },
	{ k: "direction", label: "内容方向（选填）", ph: "如：分享真实工地日常与避坑经验，顺带展示手艺", type: "area", max: 200 },
	{ k: "audience", label: "目标读者（选填）", ph: "如：准备装修的年轻业主 / 同城宝妈", type: "text", max: 100 },
	{ k: "style", label: "个人风格（选填）", ph: "如：口语化、爱自嘲、讲细节", type: "text", max: 60 },
	{ k: "proof", label: "经历背书（选填）", ph: "如：做装修 12 年，装过 300+ 套房", type: "area", max: 200 },
];
const AUTHOR_EMPTY = { name: "", role: "", industry: "", direction: "", audience: "", style: "", proof: "" };

function AuthorTab({ user, onDone }) {
	const [v, setV] = AS(AUTHOR_EMPTY);
	const [loaded, setLoaded] = AS(false);
	const [brief, setBrief] = AS("");
	const [saving, setSaving] = AS(false);
	const [tab, setTab] = AS("info");

	const load = async () => {
		try {
			const d = await NRC.api("author_get");
			setV(Object.assign({}, AUTHOR_EMPTY, d.info || {}));
			setBrief(d.brief || "");
			setLoaded(true);
		} catch (e) { AMg.error(e.message); }
	};
	AE(() => { load(); }, []);

	const setField = (k, val) => setV(prev => Object.assign({}, prev, { [k]: val }));

	const save = async () => {
		if (!v.name.trim()) { AMg.warning("称呼必填"); setTab("info"); return; }
		setSaving(true);
		try {
			const d = await NRC.api("author_save", v);
			AMg.success(d.brief ? "已保存，作者背景已更新" : "已保存（背景提炼暂未成功，再点一次保存重试）");
			if (d.brief) { setBrief(d.brief); }
			if (onDone) { onDone(); }
		} catch (e) { AMg.error(e.message); }
		finally { setSaving(false); }
	};

	//清空作者信息：回到刚登录的「先填作者信息」引导态（测试重置用；不影响已生成内容）
	const clear = async () => {
		try {
			await NRC.api("author_clear");
			setV(AUTHOR_EMPTY);
			setBrief("");
			setTab("info");
			AMg.success("已清空，回到首次填写状态");
			if (onDone) { onDone(); }
		} catch (e) { AMg.error(e.message); }
	};

	if (!loaded) {
		return <div style={{ height: "100%", display: "flex", alignItems: "center", justifyContent: "center" }}><ASp size="large" /></div>;
	}
	const undone = !(user && Number(user.author_done));

	const tabs = [
		{
			key: "info", label: "✍️ 信息", children: (
				<ACd size="small">
					{AUTHOR_FIELDS.map(f => (
						<div key={f.k} style={{ marginBottom: 16 }}>
							<div style={{ marginBottom: 6, fontSize: 14 }}>
								{f.required ? <span style={{ color: "#ff4d4f", marginRight: 4 }}>*</span> : null}{f.label}
							</div>
							{f.type === "area" ? (
								<AIp.TextArea rows={2} value={v[f.k]} maxLength={f.max} placeholder={f.ph}
									onChange={e => setField(f.k, e.target.value)} />
							) : (
								<AIp value={v[f.k]} maxLength={f.max} placeholder={f.ph}
									onChange={e => setField(f.k, e.target.value)} />
							)}
						</div>
					))}
					<div style={{ fontSize: 12, color: "#999" }}>这些字段喂给 AI 提炼「作者背景」，生成时每篇内容都带着你的身份口吻写；本人形象照在左侧「🖼 我的照片」里管理</div>
				</ACd>
			),
		},
		{
			key: "brief", label: "✨ 提炼结果", children: (
				<ACd size="small" title="作者背景（AI 提炼，每次生成自动注入，随保存自动更新）">
					{brief ? (
						<div style={{ fontSize: 13, lineHeight: 1.9, color: "#333" }}>{brief}</div>
					) : (
						<AEm image={AEm.PRESENTED_IMAGE_SIMPLE} description="保存后自动提炼；若提炼暂未成功，再点一次「保存并提炼背景」" />
					)}
				</ACd>
			),
		},
	];

	return (
		<div style={{ height: "100%", overflowY: "auto", padding: 24 }}>
			<div style={{ maxWidth: 720, margin: "0 auto" }}>
				{undone ? (
					<div style={{ marginBottom: 16, padding: "10px 14px", background: "#fff7e6", border: "1px solid #ffe7ba", borderRadius: 8, fontSize: 13 }}>
						👋 认识一下——填个称呼，再加上内容方向/目标读者/行业领域任意一项，之后每篇内容都会带着你的身份口吻写（不想填也可以直接用，随时可以回来补）
					</div>
				) : null}
				<ATabs activeKey={tab} onChange={setTab} items={tabs}
					tabBarExtraContent={<ASP>
						<APc title="清空作者信息与作者背景？（可重新填写，不影响已生成内容）" okText="清空" cancelText="取消" onConfirm={clear}>
							<ABt danger>清空</ABt>
						</APc>
						<ABt type="primary" loading={saving} onClick={save}>保存并提炼背景</ABt>
					</ASP>} />
			</div>
		</div>
	);
}

window.NRAuthorTab = AuthorTab;
