// Report Workspace — D1 report sections + AI assist

function Report({ go, route }) {
  const { snapshot } = window.useGGGSnapshot ? window.useGGGSnapshot() : { snapshot: null };
  const [activeSec, setActiveSec] = React.useState(0);
  const [reportDetail, setReportDetail] = React.useState({ report: null, sections: [], sources: [] });
  const [detailLoading, setDetailLoading] = React.useState(false);
  const [chatMessages, setChatMessages] = React.useState([]);
  const [chatInput, setChatInput] = React.useState("");
  const [chatLoading, setChatLoading] = React.useState(false);
  const [chatError, setChatError] = React.useState("");
  const [generating, setGenerating] = React.useState(false);
  const sectionRefs = React.useRef({});
  const chatInputRef = React.useRef(null);
  const routeProjectId = route?.projectId || "";
  const project = window.GGGApi?.resolveActiveProject?.(snapshot, routeProjectId) || snapshot?.projects?.[0];
  const credits = snapshot?.credits;
  const wallet = credits?.wallet || {};
  const reportSummary = project?.id
    ? latestMainReportForProject(snapshot?.reports || [], project.id) || (snapshot?.latestReport?.project_id === project.id ? snapshot.latestReport : null)
    : null;
  const report = reportDetail.report || reportSummary;
  const sections = reportDetail.report?.id === report?.id
    ? reportDetail.sections
    : (snapshot?.latestReport?.id === report?.id ? snapshot?.reportSections || [] : []);
  const sources = reportDetail.report?.id === report?.id
    ? reportDetail.sources
    : (snapshot?.latestReport?.id === report?.id ? snapshot?.reportSources || [] : []);
  const specialReports = (snapshot?.specialReports || []).filter((item) => !project?.id || item.project_id === project.id);
  const expertItems = (snapshot?.expertItems || []).filter((item) => !project?.id || item.project_id === project.id);
  const active = sections[activeSec] || sections[0];

  React.useEffect(() => {
    if (project?.id && window.GGGApi?.setActiveProjectId) window.GGGApi.setActiveProjectId(project.id);
    if (project?.id && !routeProjectId && window.location.pathname === "/report") {
      window.history.replaceState({}, "", `/report/${encodeURIComponent(project.id)}`);
    }
  }, [project?.id]);

  React.useEffect(() => {
    let mounted = true;
    setActiveSec(0);
    if (!reportSummary?.id || !window.GGGApi?.getReportById) {
      setReportDetail({ report: null, sections: [], sources: [] });
      return () => { mounted = false; };
    }
    if (snapshot?.latestReport?.id === reportSummary.id) {
      setReportDetail({
        report: snapshot.latestReport,
        sections: snapshot.reportSections || [],
        sources: snapshot.reportSources || []
      });
      return () => { mounted = false; };
    }
    setDetailLoading(true);
    window.GGGApi.getReportById(reportSummary.id)
      .then((data) => {
        if (mounted) setReportDetail({ report: data.report || reportSummary, sections: data.sections || [], sources: data.sources || [] });
      })
      .catch(() => {
        if (mounted) setReportDetail({ report: reportSummary, sections: [], sources: [] });
      })
      .finally(() => { if (mounted) setDetailLoading(false); });
    return () => { mounted = false; };
  }, [reportSummary?.id, snapshot?.latestReport?.id]);

  React.useEffect(() => {
    let mounted = true;
    setChatError("");
    setChatInput("");
    if (!active?.id || !window.GGGApi?.getReportSectionChat) {
      setChatMessages([]);
      return () => { mounted = false; };
    }
    window.GGGApi.getReportSectionChat(active.id)
      .then((data) => { if (mounted) setChatMessages(data.messages || []); })
      .catch((err) => { if (mounted) setChatError(err.message || "对话加载失败"); });
    return () => { mounted = false; };
  }, [active?.id]);

  const scrollToSection = (section, index) => {
    setActiveSec(index);
    requestAnimationFrame(() => {
      sectionRefs.current[section.id]?.scrollIntoView({ behavior: "smooth", block: "start" });
    });
  };

  const submitSectionQuestion = async (event) => {
    event.preventDefault();
    const question = (chatInput || chatInputRef.current?.value || "").trim();
    if (!question || !active?.id || chatLoading) return;
    const optimistic = { id: `local_${Date.now()}`, role: "user", message: question, created_at: new Date().toISOString() };
    setChatMessages((current) => [...current, optimistic]);
    setChatInput("");
    setChatLoading(true);
    setChatError("");
    try {
      const data = await window.GGGApi.askReportSectionQuestion(active.id, question);
      setChatMessages(data.messages || []);
    } catch (err) {
      setChatError(err.message || "AI 助手回答失败");
    } finally {
      setChatLoading(false);
    }
  };

  const generatePaidReport = async () => {
    if (!window.GGGApi || !project?.id || generating) return;
    setGenerating(true);
    try {
      await window.GGGApi.generateReportForProject(project.id);
    } finally {
      setGenerating(false);
    }
  };

  return (
    <AppShell go={go} current="report" pageBreadcrumbs={[
      { label: "项目", go: () => go("project") },
      { label: project?.name || "出海项目", go: () => project?.id ? go("project", project.id) : go("project") },
      { label: report ? `主报告 · v${report.version}` : "主报告" },
    ]}>
      <div className="page" style={{ maxWidth: 1400 }}>
        <div className="page-header">
          <div>
            <div className="row-flex" style={{ gap: 8, marginBottom: 10 }}>
              <span className="badge badge-green"><span className="badge-dot"></span>{report?.status === "completed" ? "Ready · 已就绪" : "Draft"}</span>
              <span className="badge">v{report?.version || 1} · {dateOnly(report?.updated_at || "")}</span>
              <span className="badge badge-teal">中文 · 简体</span>
              <span className="badge">可用点数 {wallet.available_credits ?? 0}</span>
            </div>
            <h1 className="page-title">{project?.name || report?.title || "市场进入报告"}</h1>
            <p className="page-sub">{project?.product_category || project?.product_name} · {project?.target_city || project?.target_region} · {project?.target_customer_segment}</p>
          </div>
          <div className="row-flex">
            <button className="btn btn-ghost btn-sm" disabled={generating} onClick={generatePaidReport}><Icon name="regen" size={14} /> {generating ? "生成中..." : "标准报告 · 80 点"}</button>
            <button className="btn btn-ghost btn-sm"><Icon name="edit" size={14} /> 编辑</button>
            <button className="btn btn-ghost btn-sm"><Icon name="bookmark" size={14} /> 保存版本</button>
            <button className="btn btn-primary btn-sm" onClick={() => window.GGGApi && window.GGGApi.downloadReport(report?.id, "pdf")}><Icon name="download" size={14} /> PDF</button>
            <button className="btn btn-ghost btn-sm" onClick={() => window.GGGApi && window.GGGApi.downloadReport(report?.id, "docx")}><Icon name="doc" size={14} /> DOCX</button>
            <button className="btn btn-ghost btn-sm" onClick={() => window.GGGApi && window.GGGApi.downloadReport(report?.id, "md")}><Icon name="file-text" size={14} /> MD</button>
          </div>
        </div>

        {detailLoading && <div className="callout info" style={{ marginBottom: 16 }}>正在加载当前项目报告章节...</div>}

        {!report && (
          <div className="card card-pad empty-report-state">
            <Icon name="file-text" size={28} />
            <h3>当前账号还没有报告</h3>
            <p>请先创建真实项目并上传资料，再调用 MCP 和 AI 生成报告。</p>
            <button className="btn btn-primary btn-sm" onClick={() => go("project-new")}><Icon name="plus" size={14} /> 创建项目</button>
          </div>
        )}

        <div className="report-shell">
          <aside className="report-toc">
            <h4 style={{ marginBottom: 10 }}>报告目录</h4>
            {sections.map((section, i) => (
              <div key={section.id} className={"toc-link " + (i === activeSec ? "active" : "")} onClick={() => scrollToSection(section, i)}>
                <span className="toc-num">{String(i + 1).padStart(2, "0")}</span>
                <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{cleanReportSectionTitle(section.title)}</span>
                <span className={"toc-status " + sectionStatus(section)} />
              </div>
            ))}
            <div className="divider" style={{ margin: "16px -4px" }} />
            <h4 style={{ marginBottom: 10 }}>专项报告 ({specialReports.length})</h4>
            {specialReports.map((item) => (
              <div key={item.id} className="toc-link" onClick={() => go("special")}>
                <Icon name={specialIcon(item.report_type)} size={13} color="var(--accent)" />
                <span style={{ flex: 1, fontSize: 13 }}>{item.title.replace("专项报告", "")}</span>
              </div>
            ))}
          </aside>

          <div className="report-main">
            <div className="report-cover">
              <div className="label">Market Entry Research Report</div>
              <h1>{report?.title || "市场进入调研报告"}</h1>
              <div className="meta">
                <span><Icon name="globe" size={14} /> {project?.target_country} · {project?.target_city}</span>
                <span><Icon name="package" size={14} /> {project?.product_category || project?.product_name}</span>
                <span><Icon name="clock" size={14} /> {dateOnly(report?.updated_at || "")}</span>
                <span><Icon name="user" size={14} /> {snapshot?.workspace?.company_name || "Good Go Global"}</span>
              </div>
            </div>
            <div className="report-body">
              {sections.map((section, index) => (
                <div
                  key={section.id}
                  className="report-section"
                  ref={(node) => {
                    if (node) sectionRefs.current[section.id] = node;
                  }}
                >
                  <div className="section-num">{String(index + 1).padStart(2, "0")} · {section.section_key}</div>
                  <h2>{cleanReportSectionTitle(section.title)}</h2>
                  <MarkdownBlocks markdown={section.markdown_content} />
                  {section.expert_required ? (
                    <div className="callout risk">
                      <div className="callout-title">需要专家确认</div>
                      本节包含 {riskLabel(section.risk_level)} 风险内容，请在执行前咨询持牌专业人士。
                    </div>
                  ) : null}
                </div>
              ))}

              <div className="source-box">
                <b>数据来源（节选）：</b>
                {sources.map((source, index) => (
                  <span key={source.id}> <span className="cite">[{index + 1}]</span> {source.title} · {source.source_date}</span>
                ))}
                <br /><br />
                本报告由 AI 基于用户输入和公开资料生成，仅用于市场调研和商业决策参考，不构成法律、税务、移民、投资、报关或认证方面的专业意见。
              </div>
            </div>
          </div>

          <aside className="report-aside">
            <div className="aside-card">
              <h4><Icon name="sparkles" size={14} color="var(--cyan)" /> AI 助手</h4>
              <div className="body">
                您正在阅读 <b>{active?.title || "报告章节"}</b>。可以基于本章节继续追问，或重新生成。
              </div>
              <div className="actions">
                <button className="aside-act" onClick={() => go("document", project?.id)}><Icon name="upload" /> 上传补充数据</button>
                <button className="aside-act" onClick={() => go("special")}><Icon name="trend" /> 生成专项报告</button>
                <button className="aside-act" onClick={generatePaidReport}><Icon name="regen" /> 重新生成报告（80 点）</button>
                <button className="aside-act" onClick={() => chatInputRef.current?.focus()}><Icon name="sparkles" /> 针对本节追问</button>
              </div>
              <form className="section-chat" onSubmit={submitSectionQuestion}>
                <label>针对本节提问</label>
                <div className="section-chat-log">
                  {chatMessages.length ? chatMessages.map((message) => (
                    <div key={message.id || `${message.role}-${message.created_at}`} className={"section-chat-msg " + (message.role === "user" ? "user" : "assistant")}>
                      <div className="role">{message.role === "user" ? "您" : "AI 助手"}</div>
                      <div className="content">{message.message}</div>
                    </div>
                  )) : (
                    <div className="section-chat-empty">输入问题后，AI 会基于本报告、本章节、数据来源和上传资料回答。</div>
                  )}
                  {chatLoading ? <div className="section-chat-empty">AI 正在阅读本节并生成回答...</div> : null}
                </div>
                {chatError ? <div className="section-chat-error">{chatError}</div> : null}
                <textarea
                  ref={chatInputRef}
                  className="textarea section-chat-input"
                  value={chatInput}
                  onChange={(event) => setChatInput(event.target.value)}
                  placeholder="例如：本节提到的主要风险里，哪些需要先找专家确认？"
                />
                <button className="btn btn-primary btn-sm btn-block" type="submit" disabled={chatLoading || !active?.id}>
                  <Icon name="send" size={13} /> {chatLoading ? "回答中..." : "发送问题"}
                </button>
              </form>
            </div>

            <div className="aside-card">
              <h4>本节置信度</h4>
              <div className="body">
                <Confidence label="价格与竞品数据" level={active?.confidence_level === "high" ? 4 : 3} tone={active?.confidence_level} />
                <Confidence label="合规判断" level={active?.risk_level === "high" ? 2 : 3} tone={active?.risk_level === "high" ? "medium" : "high"} />
                <Confidence label="市场份额估算" level={2} tone="medium" />
              </div>
            </div>

            <div className="aside-card" style={{ background: "var(--warning-soft)", borderColor: "rgba(245,158,11,0.3)" }}>
              <h4 style={{ color: "#B47308" }}><Icon name="alert" size={14} /> 需要专家确认</h4>
              <div className="body" style={{ marginTop: 8 }}>
                <div style={{ fontSize: 12.5, lineHeight: 1.55 }}>
                  当前项目涉及 <b>{expertItems.length} 项</b> 专家确认事项。
                </div>
                <button className="btn btn-soft btn-sm btn-block" style={{ marginTop: 12 }} onClick={() => go("tasks", project?.id)}>
                  查看任务确认事项
                </button>
              </div>
            </div>

            <div className="aside-card">
              <h4>数据来源（本报告）</h4>
              <div className="body" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {sources.map((source, index) => (
                  <div key={source.id} style={{ display: "flex", gap: 10, fontSize: 12, color: "var(--ink-2)" }}>
                    <span style={{ color: "var(--cyan)", fontWeight: 700, minWidth: 14 }}>{index + 1}.</span>
                    <span style={{ flex: 1 }}>{source.title}</span>
                    <span style={{ color: "var(--muted)", fontSize: 11 }}>{source.source_date}</span>
                  </div>
                ))}
              </div>
            </div>
          </aside>
        </div>
      </div>
    </AppShell>
  );
}

function MarkdownBlocks({ markdown = "" }) {
  const blocks = parseMarkdownBlocks(markdown);
  return (
    <>
      {blocks.map((block, index) => {
        if (block.type === "ul") {
          return <ul key={index}>{block.items.map((item, i) => <li key={i}>{cleanMarkdown(item)}</li>)}</ul>;
        }
        if (block.type === "table") {
          return (
            <div key={index} className="report-table">
              <table>
                <thead><tr>{block.header.map((cell, i) => <th key={i}>{cleanMarkdown(cell)}</th>)}</tr></thead>
                <tbody>{block.rows.map((row, i) => <tr key={i}>{row.map((cell, j) => <td key={j}>{cleanMarkdown(cell)}</td>)}</tr>)}</tbody>
              </table>
            </div>
          );
        }
        return <p key={index}>{cleanMarkdown(block.text)}</p>;
      })}
    </>
  );
}

function parseMarkdownBlocks(markdown) {
  const lines = String(markdown || "").split(/\r?\n/);
  const blocks = [];
  for (let i = 0; i < lines.length; i += 1) {
    const line = lines[i].trim();
    if (!line) continue;
    if (line.startsWith("|")) {
      const tableLines = [];
      while (i < lines.length && lines[i].trim().startsWith("|")) {
        tableLines.push(lines[i].trim());
        i += 1;
      }
      i -= 1;
      const rows = tableLines
        .filter((row) => !/^\|\s*-+/.test(row))
        .map((row) => row.split("|").slice(1, -1).map((cell) => cell.trim()));
      if (rows.length) blocks.push({ type: "table", header: rows[0], rows: rows.slice(1) });
      continue;
    }
    if (/^[-*]\s+/.test(line)) {
      const items = [];
      while (i < lines.length && /^[-*]\s+/.test(lines[i].trim())) {
        items.push(lines[i].trim().replace(/^[-*]\s+/, ""));
        i += 1;
      }
      i -= 1;
      blocks.push({ type: "ul", items });
      continue;
    }
    blocks.push({ type: "p", text: line.replace(/^#{1,4}\s+/, "") });
  }
  return blocks;
}

function cleanMarkdown(value = "") {
  return String(value).replace(/\*\*/g, "").replace(/`/g, "");
}

function cleanReportSectionTitle(value = "") {
  return String(value)
    .replace(/^\s*(第[一二三四五六七八九十百千万]+[章节篇部分]|[一二三四五六七八九十百千万]+|[0-9]+)\s*(?:[、.．:：-]\s*|\s+)/u, "")
    .trim();
}

function latestMainReportForProject(reports = [], projectId = "") {
  if (!projectId) return null;
  return [...reports]
    .filter((report) => report.project_id === projectId && (report.report_type || "main") === "main")
    .sort((a, b) => String(b.updated_at || b.created_at || "").localeCompare(String(a.updated_at || a.created_at || "")) || Number(b.version || 0) - Number(a.version || 0))[0] || null;
}

function sectionStatus(section) {
  if (section.risk_level === "high") return "risk";
  if (section.expert_required || section.risk_level === "medium") return "warn";
  return "ok";
}

function specialIcon(type) {
  if (type === "marketing") return "trend";
  if (type === "logistics") return "truck";
  if (type === "trademark") return "tag";
  return "file-text";
}

function Confidence({ label, level, tone }) {
  return (
    <>
      <div className="space-between" style={{ marginTop: 12 }}>
        <span style={{ fontSize: 12.5 }}>{label}</span>
        <span className={"badge badge-" + (tone === "high" ? "green" : "orange")} style={{ padding: "1px 6px", fontSize: 10 }}>{tone === "high" ? "高" : "中"}</span>
      </div>
      <div className="confidence">
        {[0, 1, 2, 3, 4].map((i) => <span key={i} className={i < level ? "on" : ""} />)}
      </div>
    </>
  );
}

window.Report = Report;
