// Atlas · Step 3 — Outline (dynamic from real parsedScope + outline)
const { useState: useStateOutline } = React;

function StepOutline({ outline: outlineRaw, setOutline, reportId, parsedScope, intake, goBack, goNext, goForward, readOnly }) {
  const outline = Array.isArray(outlineRaw) ? outlineRaw : [];
  const [chat, setChat] = useStateOutline("");
  const [chatLoading, setChatLoading] = useStateOutline(false);
  const [revisionDone, setRevisionDone] = useStateOutline(false);
  const [changeSummary, setChangeSummary] = useStateOutline(null);
  const [flags, setFlags] = useStateOutline([]);
  const [dismissedFlags, setDismissedFlags] = useStateOutline(new Set());
  const [previousOutline, setPreviousOutline] = useStateOutline(null);

  const clean = (s) => s ? s.replace(/<[^>]+>/g, "") : "";

  const flagIcon = (type) => ({ COVERAGE_GAP: "⚠", OUT_OF_SCOPE: "⚠", SCOPE_DRIFT: "ℹ", STRUCTURAL_WARNING: "·" }[type] || "·");

  const handleUndo = async () => {
    if (!previousOutline) return;
    setOutline(previousOutline);
    setFlags([]);
    setDismissedFlags(new Set());
    setPreviousOutline(null);
    setRevisionDone(false);
    setChangeSummary(null);
    try {
      await fetch(`/api/outline/${reportId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ chapters: previousOutline }),
      });
    } catch (_) {}
  };

  const { FORMATS } = window.ATLAS_DATA;
  const formatLabel = FORMATS.find((f) => f.id === (intake?.format || "pptx"))?.label || "PowerPoint";

  const title = parsedScope?.title || "Your report";
  const subtitle = parsedScope?.subtitle || "";
  const allQuestions = parsedScope?.questions || [];

  // "Q1, Q3" → "questions 1 and 3"
  const formatQuestionRefs = (str) => {
    if (!str) return null;
    const nums = str.match(/\d+/g);
    if (!nums || nums.length === 0) return null;
    const labels = nums.map(n => n);
    if (labels.length === 1) return `question ${labels[0]}`;
    return `questions ${labels.slice(0, -1).join(", ")} and ${labels[labels.length - 1]}`;
  };

  return (
    <div className="canvas-inner">
      {readOnly && (
        <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 14px", marginBottom: 12,
          background: "var(--ink-1)", border: "1px solid var(--ink-2)", borderRadius: "var(--radius)",
          fontSize: 12, color: "var(--ink-4)" }}>
          <Icon name="info" size={13} />
          This report has been researched. The outline is view-only.
        </div>
      )}
      <div className="outline-clean">
        <p className="outline-intro">
          Atlas will deliver a <strong>{formatLabel}</strong> with{" "}
          <strong>{outline.length > 0 ? outline.length : "the"} chapter{outline.length !== 1 ? "s" : ""}</strong>{" "}
          outlined below. Review and request any changes before approving.
        </p>

        {/* Chat with Outline Agent */}
        {!readOnly && <div className="outline-chat-top">
          <div className="av"><Icon name="bot" size={15} /></div>
          <div className="body">
            <div className="h">Anything you'd change?</div>
            <div className="s">Tell the agent what to change, then approve when it looks right.</div>
            <textarea
              placeholder='e.g. "Add a chapter on regulatory landscape" or "Reorder so competitive analysis comes first."'
              value={chat}
              onChange={(e) => { setChat(e.target.value); setRevisionDone(false); setChangeSummary(null); setFlags([]); setDismissedFlags(new Set()); setPreviousOutline(null); }}
            />
            <details className="outline-capabilities">
              <summary>What can I ask?</summary>
              <ul>
                <li>Add, remove, rename, or reorder any section</li>
                <li>Split one chapter into multiple, or merge several into one</li>
                <li>Specify a custom section order ("I want competitive analysis first, then market sizing")</li>
                <li>Impose a specific template structure ("Use these exact section titles: …")</li>
                <li>Group research questions by theme into fewer, broader chapters</li>
              </ul>
            </details>
            <div className="row">
              <span></span>
              <button
                className="btn primary sm"
                disabled={!chat.trim() || chatLoading}
                onClick={async () => {
                  if (!reportId || !chat.trim()) return;
                  setChatLoading(true);
                  try {
                    const res = await fetch(`/api/outline/${reportId}`, {
                      method: "POST",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify({ revision: chat, current_outline: outline }),
                    });
                    if (res.ok) {
                      const data = await res.json();
                      const updated = Array.isArray(data.outline) ? data.outline : [];
                      setPreviousOutline(outline);
                      setOutline(updated);
                      setFlags(data.flags || []);
                      setDismissedFlags(new Set());
                      setRevisionDone(true);
                      setChangeSummary(data.change_summary || null);
                      setChat("");
                    } else {
                      const err = await res.json().catch(() => ({}));
                      alert("Revision failed: " + (err.detail || res.status));
                    }
                  } catch (e) { alert("Revision error: " + e.message); } finally { setChatLoading(false); }
                }}
              >
                <Icon name="send" size={11} /> {chatLoading ? "Revising…" : "Send to agent"}
              </button>
            </div>
          </div>
        </div>}

        {/* Changes applied confirmation */}
        {revisionDone && (
          <div style={{ marginBottom: 16, padding: "8px 12px", background: "var(--success-tint)",
            border: "1px solid var(--success-line)", borderRadius: "var(--radius)",
            fontSize: 12, color: "var(--success)", fontFamily: "var(--mono)" }}>
            ✓ {changeSummary || "Changes applied to outline."}
          </div>
        )}

        {/* Flag banners */}
        {(() => {
          const visibleFlags = flags.filter(f => !dismissedFlags.has(f.type + f.message));
          return (<>
            {previousOutline && (
              <button className="outline-flag-undo" onClick={handleUndo}>Undo</button>
            )}
            {visibleFlags.map((f, i) => (
              <div key={i} className={`outline-flag outline-flag--${f.type.toLowerCase()}`}>
                <span>{flagIcon(f.type)} {f.message}</span>
                <div className="outline-flag-actions">
                  <button className="outline-flag-dismiss" onClick={() => setDismissedFlags(prev => new Set([...prev, f.type + f.message]))}>×</button>
                </div>
              </div>
            ))}
          </>);
        })()}

        {/* Outline list */}
        <div className="outline-list">
          <div className="header">
            <span className="label">Outline · {outline.length} chapter{outline.length !== 1 ? "s" : ""}</span>
          </div>
          {outline.length === 0 ? (
            <div style={{ padding: "32px 0", textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>
              No chapters yet. Outline is being generated.
            </div>
          ) : (
            outline.map((c, i) => (
              <div className="outline-row" key={c.id || i}>
                <span className="num">{String(i + 1).padStart(2, "0")}</span>
                <div className="body">
                  <h4 className="ttl">{c.title}</h4>
                  <p className="desc">
                    {clean(c.blurb)}
                    {formatQuestionRefs(c.addresses_questions) && (
                      <span style={{ color: "var(--ink-4)" }}>{" "}Covers {formatQuestionRefs(c.addresses_questions)}.</span>
                    )}
                  </p>
                </div>
              </div>
            ))
          )}
        </div>
      </div>

      <div className="actionbar">
        <div className="left">
          {readOnly
            ? <span style={{ color: "var(--ink-4)", fontSize: 12 }}>View only</span>
            : <>Saved as <span className="kbd">outline.md</span></>}
        </div>
        <div className="right">
          <button className="btn ghost" onClick={goBack}>
            <Icon name="arrowLeft" size={14} /> Back to scope
          </button>
          {readOnly && <button className="btn ghost" onClick={goForward}>View research <Icon name="arrowRight" size={14} /></button>}
          {!readOnly && (
            <button className="btn primary lg" disabled={outline.length === 0} onClick={goNext}>
              Approve outline &amp; start research
              <Icon name="arrowRight" size={14} />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

window.StepOutline = StepOutline;
