// Settings page

function Settings({ go }) {
  const [section, setSection] = React.useState(() => sanitizeSettingsSection(window.GGGSettingsDefaultSection || "profile"));
  const { t } = window.useI18n ? window.useI18n() : { t: (key) => key };
  const { snapshot } = window.useGGGSnapshot ? window.useGGGSnapshot() : { snapshot: null };
  const workspace = snapshot?.workspace;
  React.useEffect(() => {
    if (!window.GGGSettingsDefaultSection) return;
    setSection(sanitizeSettingsSection(window.GGGSettingsDefaultSection));
    window.GGGSettingsDefaultSection = "";
  }, []);
  return (
    <AppShell go={go} current="settings" pageTitle="设置">
      <div className="page page-narrow">
        <div className="page-header">
          <div>
            <h1 className="page-title">账户设置</h1>
            <p className="page-sub">管理您的资料、数据隐私和通知偏好。点数充值与消费流水请前往主菜单「点数中心」。</p>
          </div>
        </div>

        <div className="settings-grid">
          <nav className="settings-nav">
            {[
              { key: "profile", lbl: "个人资料", icon: "user" },
              { key: "company", lbl: "企业资料", icon: "office" },
              { key: "language", lbl: t("settings.nav.language"), icon: "languages" },
              { key: "reportPrefs", lbl: t("settings.nav.report"), icon: "file-text" },
              { key: "privacy", lbl: "数据隐私", icon: "shield" },
              { key: "team", lbl: "团队成员", icon: "users" },
              { key: "notif", lbl: "通知", icon: "bell" },
              { key: "danger", lbl: "账户操作", icon: "alert" },
            ].map(n => (
              <button key={n.key} className={section === n.key ? "active" : ""} onClick={() => setSection(n.key)}>
                <Icon name={n.icon} size={14} />
                <span>{n.lbl}</span>
              </button>
            ))}
          </nav>

          <div>
            {section === "profile" && <ProfileSec workspace={workspace} user={snapshot?.user} />}
            {section === "company" && <CompanySec workspace={workspace} />}
            {section === "language" && <LanguageSec workspace={workspace} />}
            {section === "reportPrefs" && <ReportSec workspace={workspace} />}
            {section === "privacy" && <PrivacySec />}
            {section === "team" && <TeamSec />}
            {section === "notif" && <NotifSec />}
            {section === "danger" && <DangerSec />}
          </div>
        </div>
      </div>
    </AppShell>
  );
}

function sanitizeSettingsSection(section) {
  return ["profile", "company", "language", "reportPrefs", "privacy", "team", "notif", "danger"].includes(section) ? section : "profile";
}

function Sec({ title, sub, children }) {
  return (
    <div className="settings-sec">
      <h3>{title}</h3>
      {sub && <p className="sub">{sub}</p>}
      <div style={{ marginTop: 22 }}>{children}</div>
    </div>
  );
}

function ProfileSec({ workspace, user }) {
  const metadata = parseJson(workspace?.metadata, {});
  const fileRef = React.useRef(null);
  const [form, setForm] = React.useState({
    displayName: workspace?.display_name || "",
    roleTitle: workspace?.role_title || "",
    email: user?.email || "",
    phone: metadata.phone || "",
    city: workspace?.city || "",
    timezone: workspace?.timezone || "Asia/Shanghai",
  });
  const [status, setStatus] = React.useState("");
  const [error, setError] = React.useState("");
  React.useEffect(() => {
    const nextMeta = parseJson(workspace?.metadata, {});
    setForm({
      displayName: workspace?.display_name || "",
      roleTitle: workspace?.role_title || "",
      email: user?.email || "",
      phone: nextMeta.phone || "",
      city: workspace?.city || "",
      timezone: workspace?.timezone || "Asia/Shanghai",
    });
  }, [workspace?.id, workspace?.updated_at, user?.email]);
  const update = (key, value) => setForm((current) => ({ ...current, [key]: value }));
  const save = async () => {
    setError("");
    setStatus("");
    try {
      await window.GGGApi.saveAccountProfile(form);
      setStatus("已保存");
    } catch (err) {
      setError(err.message || "保存失败");
    }
  };
  const uploadAvatar = async (file) => {
    if (!file) return;
    setError("");
    setStatus("");
    try {
      await window.GGGApi.uploadAvatar(file);
      setStatus("头像已保存");
    } catch (err) {
      setError(err.message || "头像上传失败");
    } finally {
      if (fileRef.current) fileRef.current.value = "";
    }
  };
  return (
    <>
      <Sec title="个人资料" sub="这些信息会显示在团队成员和报告作者栏。">
        <div style={{ display: "flex", gap: 18, alignItems: "center", marginBottom: 22 }}>
          <div className="avatar" style={{ width: 64, height: 64, fontSize: 22, overflow: "hidden" }}>
            {workspace?.avatar_url ? <img src={workspace.avatar_url} alt="avatar" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : (workspace?.initials || "GG")}
          </div>
          <div>
            <input ref={fileRef} type="file" accept="image/png,image/jpeg" style={{ display: "none" }} onChange={(event) => uploadAvatar(event.target.files?.[0])} />
            <button className="btn btn-ghost btn-sm" type="button" onClick={() => fileRef.current?.click()}>更换头像</button>
            <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 6 }}>JPG / PNG · 最大 2MB</div>
          </div>
        </div>
        {(status || error) && <div className={error ? "form-alert" : "callout info"} style={{ marginBottom: 16 }}>{error || status}</div>}
        <div className="form-grid">
          <div className="field"><label className="field-label">姓名</label><input className="input" value={form.displayName} onChange={(e) => update("displayName", e.target.value)} /></div>
          <div className="field"><label className="field-label">职位</label><input className="input" value={form.roleTitle} onChange={(e) => update("roleTitle", e.target.value)} /></div>
          <div className="field"><label className="field-label">邮箱</label><input className="input" value={form.email} readOnly /></div>
          <div className="field"><label className="field-label">手机</label><input className="input" value={form.phone} onChange={(e) => update("phone", e.target.value)} /></div>
          <div className="field"><label className="field-label">所在城市</label><input className="input" value={form.city} onChange={(e) => update("city", e.target.value)} /></div>
          <div className="field"><label className="field-label">所在时区</label><select className="select" value={form.timezone} onChange={(e) => update("timezone", e.target.value)}><option>Asia/Shanghai</option><option>America/Toronto</option></select></div>
        </div>
        <div style={{ marginTop: 22, display: "flex", justifyContent: "flex-end", gap: 10 }}>
          <button className="btn btn-ghost" type="button" onClick={() => window.GGGApi.loadAppSnapshot()}>取消</button>
          <button className="btn btn-primary" type="button" onClick={save}>保存修改</button>
        </div>
      </Sec>
    </>
  );
}

function CompanySec({ workspace }) {
  const metadata = parseJson(workspace?.metadata, {});
  const [form, setForm] = React.useState({
    companyName: workspace?.company_name || "",
    companyEnglishName: workspace?.company_english_name || "",
    primaryCategory: metadata.primaryCategory || "家居用品",
    annualOutput: metadata.annualOutput || "1000 万 - 5000 万",
    companyBio: metadata.companyBio || "",
  });
  const [status, setStatus] = React.useState("");
  const [error, setError] = React.useState("");
  React.useEffect(() => {
    const nextMeta = parseJson(workspace?.metadata, {});
    setForm({
      companyName: workspace?.company_name || "",
      companyEnglishName: workspace?.company_english_name || "",
      primaryCategory: nextMeta.primaryCategory || "家居用品",
      annualOutput: nextMeta.annualOutput || "1000 万 - 5000 万",
      companyBio: nextMeta.companyBio || "",
    });
  }, [workspace?.id, workspace?.updated_at]);
  const update = (key, value) => setForm((current) => ({ ...current, [key]: value }));
  const save = async () => {
    setError("");
    setStatus("");
    try {
      await window.GGGApi.saveAccountCompany(form);
      setStatus("已保存");
    } catch (err) {
      setError(err.message || "保存失败");
    }
  };
  return (
    <Sec title="企业资料" sub="用于生成报告页眉、商业计划书和服务转介。">
      {(status || error) && <div className={error ? "form-alert" : "callout info"} style={{ marginBottom: 16 }}>{error || status}</div>}
      <div className="form-grid">
        <div className="field"><label className="field-label">公司名称</label><input className="input" value={form.companyName} onChange={(e) => update("companyName", e.target.value)} /></div>
        <div className="field"><label className="field-label">公司英文名</label><input className="input" value={form.companyEnglishName} onChange={(e) => update("companyEnglishName", e.target.value)} /></div>
        <div className="field"><label className="field-label">主要品类</label><select className="select" value={form.primaryCategory} onChange={(e) => update("primaryCategory", e.target.value)}><option>家居用品</option><option>食品 / 餐饮</option><option>工业品</option><option>服装成衣</option></select></div>
        <div className="field"><label className="field-label">年产值</label><select className="select" value={form.annualOutput} onChange={(e) => update("annualOutput", e.target.value)}><option>1000 万 - 5000 万</option><option>5000 万 - 1 亿</option><option>1 亿以上</option></select></div>
        <div className="field full"><label className="field-label">公司简介</label><textarea className="textarea" value={form.companyBio} onChange={(e) => update("companyBio", e.target.value)} /></div>
      </div>
      <div style={{ marginTop: 22, display: "flex", justifyContent: "flex-end", gap: 10 }}>
        <button className="btn btn-primary" type="button" onClick={save}>保存修改</button>
      </div>
    </Sec>
  );
}

function LanguageSec({ workspace }) {
  const { lang, setLanguage, t } = window.useI18n ? window.useI18n() : { lang: "zh", setLanguage: () => {}, t: (key) => key };
  const [status, setStatus] = React.useState("");
  const [error, setError] = React.useState("");
  const save = async () => {
    setError("");
    setStatus("");
    try {
      await window.GGGApi.saveAccountPreferences({
        locale: lang === "en" ? "en" : "zh-CN",
      });
      setStatus("已保存");
    } catch (err) {
      setError(err.message || "保存失败");
    }
  };
  return (
    <Sec title={t("settings.language.title")} sub={t("settings.language.subtitle")}>
      {(status || error) && <div className={error ? "form-alert" : "callout info"} style={{ marginBottom: 16 }}>{error || status}</div>}
      <div className="form-grid">
        <div className="field">
          <label className="field-label">界面语言</label>
          <div className="row-flex">
            <button type="button" className={"chip " + (lang === "zh" ? "active" : "")} onClick={() => setLanguage("zh")}>中文</button>
            <button type="button" className={"chip " + (lang === "en" ? "active" : "")} onClick={() => setLanguage("en")}>English</button>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 22, display: "flex", justifyContent: "flex-end", gap: 10 }}>
        <button className="btn btn-primary" type="button" onClick={save}>{t("settings.saveLanguage")}</button>
      </div>
    </Sec>
  );
}

function ReportSec({ workspace }) {
  const { t } = window.useI18n ? window.useI18n() : { t: (key) => key };
  const metadata = parseJson(workspace?.metadata, {});
  const [reportDefaultLanguage, setReportDefaultLanguage] = React.useState(metadata.reportDefaultLanguage || "bilingual");
  const [reportDepth, setReportDepth] = React.useState(metadata.reportDepth || "standard");
  const [status, setStatus] = React.useState("");
  const [error, setError] = React.useState("");
  React.useEffect(() => {
    const nextMeta = parseJson(workspace?.metadata, {});
    setReportDefaultLanguage(nextMeta.reportDefaultLanguage || "bilingual");
    setReportDepth(nextMeta.reportDepth || "standard");
  }, [workspace?.id, workspace?.updated_at]);
  const save = async () => {
    setError("");
    setStatus("");
    try {
      await window.GGGApi.saveAccountPreferences({
        reportDefaultLanguage,
        reportDepth,
      });
      setStatus("已保存");
    } catch (err) {
      setError(err.message || "保存失败");
    }
  };
  return (
    <Sec title={t("settings.report.title")} sub={t("settings.report.subtitle")}>
      {(status || error) && <div className={error ? "form-alert" : "callout info"} style={{ marginBottom: 16 }}>{error || status}</div>}
      <div className="form-grid">
        <div className="field">
          <label className="field-label">报告默认语言</label>
          <div className="row-flex">
            <button type="button" className={"chip " + (reportDefaultLanguage === "bilingual" ? "active" : "")} onClick={() => setReportDefaultLanguage("bilingual")}>中英双语</button>
            <button type="button" className={"chip " + (reportDefaultLanguage === "zh-CN" ? "active" : "")} onClick={() => setReportDefaultLanguage("zh-CN")}>仅中文</button>
            <button type="button" className={"chip " + (reportDefaultLanguage === "en" ? "active" : "")} onClick={() => setReportDefaultLanguage("en")}>仅 English</button>
          </div>
        </div>
        <div className="field full">
          <label className="field-label">报告深度偏好</label>
          <div className="row-flex">
            <button type="button" className={"chip " + (reportDepth === "brief" ? "active" : "")} onClick={() => setReportDepth("brief")}>简版 (3-5 章)</button>
            <button type="button" className={"chip " + (reportDepth === "standard" ? "active" : "")} onClick={() => setReportDepth("standard")}>标准版 (10-12 章)</button>
            <button type="button" className={"chip " + (reportDepth === "deep" ? "active" : "")} onClick={() => setReportDepth("deep")}>深度版 (15+ 章)</button>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 22, display: "flex", justifyContent: "flex-end", gap: 10 }}>
        <button className="btn btn-primary" type="button" onClick={save}>{t("settings.saveReport")}</button>
      </div>
    </Sec>
  );
}

function parseJson(value, fallback) {
  try { return value ? JSON.parse(value) : fallback; } catch { return fallback; }
}

function PrivacySec() {
  return (
    <Sec title="数据隐私" sub="您的产品资料和报告内容受加密保护。我们不使用您的私有数据训练 AI 模型。">
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {[
          { lbl: "文件加密存储", sub: "上传文件以 AES-256 加密存储，仅您可访问。", on: true },
          { lbl: "禁止用于模型训练", sub: "您的私有资料不会被用于 AI 模型训练或其他用户。", on: true },
          { lbl: "项目权限隔离", sub: "每个项目独立访问控制，团队成员需单独授权。", on: true },
          { lbl: "审计日志", sub: "所有项目访问、修改、导出记录可追溯。", on: false },
        ].map((p, i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: 14, border: "1px solid var(--line)", borderRadius: 10 }}>
            <div>
              <div style={{ fontWeight: 500, fontSize: 14 }}>{p.lbl}</div>
              <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 3 }}>{p.sub}</div>
            </div>
            <Toggle on={p.on} />
          </div>
        ))}
      </div>
      <div className="divider" />
      <div className="row-flex" style={{ gap: 10 }}>
        <button className="btn btn-ghost"><Icon name="download" size={14} /> 导出我的全部数据</button>
        <button className="btn btn-ghost" style={{ color: "var(--red)", borderColor: "rgba(220,38,38,0.3)" }}>清空所有项目资料</button>
      </div>
    </Sec>
  );
}

function TeamSec() {
  return (
    <Sec title="团队成员" sub="邀请合作者加入项目。Business 计划支持最多 10 名成员。">
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {[
          { name: "陈丽华", role: "Owner", email: "lihua@hyhome.com", initial: "CL" },
          { name: "Tony Wang", role: "Editor", email: "tony@hyhome.com", initial: "TW" },
          { name: "Sarah Chen", role: "Viewer", email: "sarah@partner.com", initial: "SC" },
        ].map((m, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: 12, border: "1px solid var(--line)", borderRadius: 10 }}>
            <div className="avatar" style={{ width: 36, height: 36 }}>{m.initial}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{m.name}</div>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{m.email}</div>
            </div>
            <select className="select" style={{ width: 110, padding: "6px 10px", fontSize: 13 }}><option>{m.role}</option><option>Owner</option><option>Editor</option><option>Viewer</option></select>
            <button style={{ color: "var(--muted)", padding: 6 }}><Icon name="more" size={16} /></button>
          </div>
        ))}
      </div>
      <button className="btn btn-soft btn-sm" style={{ marginTop: 16 }}><Icon name="plus" size={14} /> 邀请新成员</button>
    </Sec>
  );
}

function NotifSec() {
  return (
    <Sec title="通知偏好" sub="选择您希望接收哪些类型的提醒。">
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {[
          { lbl: "报告生成完成", on: true, channel: "邮件 + 应用内" },
          { lbl: "AI 发现关键缺失信息", on: true, channel: "应用内" },
          { lbl: "团队成员评论 / 修改", on: true, channel: "邮件" },
          { lbl: "订阅 / 账单提醒", on: true, channel: "邮件" },
          { lbl: "产品更新与新功能", on: false, channel: "邮件 (每月摘要)" },
        ].map((n, i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 0", borderBottom: "1px solid var(--line-2)" }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{n.lbl}</div>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{n.channel}</div>
            </div>
            <Toggle on={n.on} />
          </div>
        ))}
      </div>
    </Sec>
  );
}

function DangerSec() {
  return (
    <Sec title="账户操作">
      <div style={{ padding: 20, border: "1px solid rgba(220,38,38,0.2)", borderRadius: 10, background: "rgba(220,38,38,0.03)" }}>
        <h4 style={{ fontSize: 14, fontWeight: 600 }}>删除账户</h4>
        <p style={{ fontSize: 13, color: "var(--muted)", marginTop: 6, lineHeight: 1.5 }}>
          一旦删除，您的所有项目、报告和上传文件将被永久销毁，无法恢复。订阅会立即取消，未消费部分不予退款。
        </p>
        <button className="btn btn-ghost" style={{ marginTop: 14, color: "var(--red)", borderColor: "rgba(220,38,38,0.3)" }}>永久删除我的账户</button>
      </div>
    </Sec>
  );
}

function Toggle({ on }) {
  const [v, setV] = React.useState(on);
  return (
    <button onClick={() => setV(!v)} style={{
      width: 40, height: 22, borderRadius: 999,
      background: v ? "var(--teal)" : "var(--line)",
      position: "relative", transition: "background .2s", flexShrink: 0,
    }}>
      <span style={{
        position: "absolute", top: 2, left: v ? 20 : 2,
        width: 18, height: 18, borderRadius: 999, background: "white",
        boxShadow: "0 1px 3px rgba(0,0,0,0.2)", transition: "left .2s",
      }} />
    </button>
  );
}

window.Settings = Settings;
