// Review screen — lets user adjust any answer before submitting
const ReviewScreen = (function () {
  function answerDisplay(q, a) {
    if (!a) return null;
    if (q.type === "multi") {
      const opts = a.options || [];
      if (opts.length === 0 && !a.other) return null;
      return (
        <span>
          {opts.join(", ")}
          {a.other && <span style={{color:"var(--muted)"}}> · also: {a.other}</span>}
        </span>
      );
    }
    if (q.type === "table") {
      const cells = Object.entries(a);
      if (cells.length === 0) return null;
      return <span>{cells.length} entries recorded</span>;
    }
    if (q.type === "longtext") return a.text ? <span>"{a.text.slice(0,140)}{a.text.length>140?'…':''}"</span> : null;
    if (a.value) return (
      <span>
        {a.value}
        {a.text && <span style={{display:"block",fontSize:13,fontWeight:400,color:"var(--ink-2)",marginTop:4}}>↳ {a.text}</span>}
      </span>
    );
    return null;
  }

  function EditPanel({ q, value, onChange, onClose }) {
    const [draft, setDraft] = useState(value || {});
    function save() { onChange(draft); onClose(); }

    return (
      <div className="review-edit">
        {q.type === "single" && (
          <div className="opt-list">
            {q.options.map(opt => (
              <div key={opt} className={"opt radio " + (draft.value === opt ? "selected" : "")}
                onClick={() => setDraft({...draft, value: opt})}>
                <div className="box"></div><div>{opt}</div>
              </div>
            ))}
            {q.followup && draft.value && q.followup.when.includes(draft.value) && (
              <textarea
                placeholder={q.followup.label}
                value={draft.text || ""}
                onChange={e => setDraft({...draft, text: e.target.value})}
              />
            )}
          </div>
        )}
        {q.type === "multi" && (
          <div className={"opt-list " + (q.options.length > 4 ? "cols-2" : "")}>
            {q.options.map(opt => {
              const opts = draft.options || [];
              const sel = opts.includes(opt);
              return (
                <div key={opt} className={"opt " + (sel ? "selected" : "")}
                  onClick={() => setDraft({
                    ...draft,
                    options: sel ? opts.filter(o => o !== opt) : [...opts, opt]
                  })}>
                  <div className="box"></div><div>{opt}</div>
                </div>
              );
            })}
            {q.allowOther && (
              <input type="text" placeholder="Other (optional)" value={draft.other || ""} onChange={e => setDraft({...draft, other: e.target.value})} />
            )}
          </div>
        )}
        {q.type === "longtext" && (
          <textarea style={{minHeight:120}} value={draft.text || ""} onChange={e => setDraft({...draft, text: e.target.value})} placeholder={q.placeholder} />
        )}
        {q.type === "table" && (
          <div className="tools-table">
            <div className="row head">
              <div className="cell">Tool</div>
              {q.columns.map(c => <div key={c.id} className="cell">{c.label}</div>)}
            </div>
            {q.tools.map(tool => (
              <div className="row" key={tool}>
                <div className="cell tool">{tool}</div>
                {q.columns.map(col => (
                  <div className="cell" key={col.id}>
                    {col.options.map(opt => {
                      const k = tool + "::" + col.id;
                      const sel = draft[k] === opt;
                      const cls = "chip " + (opt==="Yes"?"yes ":"") + (opt==="No"?"no ":"") + (sel?"selected":"");
                      return <button key={opt} className={cls} onClick={() => {
                        const next = {...draft}; if (next[k] === opt) delete next[k]; else next[k] = opt;
                        setDraft(next);
                      }}>{opt}</button>;
                    })}
                  </div>
                ))}
              </div>
            ))}
          </div>
        )}
        <div className="edit-actions">
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={save}>Save change</button>
        </div>
      </div>
    );
  }

  function ReviewScreen({ user, answers, setAnswers, confidences, onLogout, onSubmit, onBack, fromMode }) {
    const [editingId, setEditingId] = useState(null);
    const sections = window.SURVEY.sections;

    const total = window.SURVEY_FLAT.length;
    const filled = window.SURVEY_FLAT.filter(q => {
      const a = answers[q.id];
      if (!a) return false;
      if (a.options) return a.options.length > 0;
      if (a.value) return true;
      if (a.text) return true;
      if (typeof a === "object" && Object.keys(a).length > 0) return true;
      return false;
    });
    const inferred = filled.filter(q => confidences[q.id] !== undefined);
    const lowConf = inferred.filter(q => confidences[q.id] < 0.8);

    return (
      <>
        <Topbar user={user} onLogout={onLogout} crumb="Review your answers" />
        <div className="review-shell">
          <h1>Review &amp; adjust</h1>
          <p className="lead">
            {fromMode === "chat"
              ? <>Here's everything I captured from our conversation. Anything I inferred with lower confidence is highlighted — give it a quick scan and adjust anything that doesn't look right before submitting.</>
              : <>You're almost done. Take a moment to review your responses, then submit.</>
            }
          </p>

          {fromMode === "chat" && lowConf.length > 0 && (
            <div style={{
              padding: "14px 18px", background: "#fdf1d6", border: "1px solid #f0d28a",
              borderRadius: "var(--radius)", marginBottom: 24, fontSize: 14, color: "#6b4912"
            }}>
              <strong>{lowConf.length} answer{lowConf.length > 1 ? "s" : ""}</strong> with lower confidence — worth a quick check:
              {" "}{lowConf.slice(0,5).map(q => <span key={q.id} style={{
                fontFamily:"var(--mono)", fontSize:11, padding:"2px 6px",
                background:"white", borderRadius:4, marginLeft:6
              }}>{q.id.toUpperCase()}</span>)}
              {lowConf.length > 5 && <span> +{lowConf.length-5} more</span>}
            </div>
          )}

          {sections.map(s => (
            <div className="review-section" key={s.id}>
              <h3>{s.title}</h3>
              <div className="scount">
                {s.questions.filter(q => filled.find(f => f.id === q.id)).length} of {s.questions.length} answered
              </div>
              {s.questions.map(q => {
                const a = answers[q.id];
                const isEditing = editingId === q.id;
                const display = answerDisplay(q, a);
                const conf = confidences[q.id];
                return (
                  <div key={q.id}>
                    <div className="review-q">
                      <div>
                        <div className="qprompt">
                          <span className="qid">{q.id.toUpperCase()}</span>
                          {q.prompt}
                        </div>
                        {display
                          ? <div className="qanswer">
                              {display}
                              {conf !== undefined && (
                                <span style={{marginLeft:10, fontSize:11, fontWeight:700, padding:"2px 6px", borderRadius:4,
                                  background: conf >= 0.8 ? "#d8f0d4" : conf >= 0.65 ? "#fdf1d6" : "#fde4df",
                                  color: conf >= 0.8 ? "#2c6d1d" : conf >= 0.65 ? "#8a5a14" : "#944029"
                                }}>
                                  AI · {Math.round(conf * 100)}%
                                </span>
                              )}
                            </div>
                          : <div className="qanswer unanswered">Not yet answered</div>
                        }
                      </div>
                      <button className="edit-btn" onClick={() => setEditingId(isEditing ? null : q.id)}>
                        {isEditing ? "Close" : (display ? "Edit" : "Answer")}
                      </button>
                    </div>
                    {isEditing && (
                      <EditPanel
                        q={q}
                        value={a}
                        onChange={v => setAnswers(prev => ({...prev, [q.id]: v}))}
                        onClose={() => setEditingId(null)}
                      />
                    )}
                  </div>
                );
              })}
            </div>
          ))}

          <div className="submit-bar">
            <div className="summary">
              <strong>{filled.length} of {total}</strong> questions answered
              {inferred.length > 0 && <span> · {inferred.length} inferred from chat</span>}
            </div>
            <button className="btn ghost" onClick={onBack}>← Back</button>
            <button className="btn primary" onClick={onSubmit}>Submit responses</button>
          </div>
        </div>
      </>
    );
  }

  return ReviewScreen;
})();

window.ReviewScreen = ReviewScreen;
