// Standard survey component — section-by-section walkthrough
const StandardSurvey = (function () {
  function Option({ label, selected, onClick, radio }) {
    return (
      <div className={"opt " + (radio ? "radio " : "") + (selected ? "selected" : "")} onClick={onClick}>
        <div className="box"></div>
        <div>{label}</div>
      </div>
    );
  }

  function SingleChoice({ q, value, onChange }) {
    return (
      <div className={"opt-list " + (q.options.length > 4 ? "" : "")}>
        {q.options.map(opt => (
          <Option key={opt} label={opt} radio
            selected={value?.value === opt}
            onClick={() => onChange({ value: opt, text: value?.text || "" })}
          />
        ))}
        {q.followup && value?.value && q.followup.when.includes(value.value) && (
          <div>
            <div className="followup-label">{q.followup.label}</div>
            <textarea
              value={value.text || ""}
              onChange={e => onChange({ ...value, text: e.target.value })}
              placeholder="Add detail (optional)"
            />
          </div>
        )}
      </div>
    );
  }

  function MultiChoice({ q, value, onChange }) {
    const opts = value?.options || [];
    function toggle(opt) {
      const next = opts.includes(opt) ? opts.filter(o => o !== opt) : [...opts, opt];
      onChange({ ...value, options: next });
    }
    return (
      <>
        <div className={"opt-list " + (q.options.length > 4 ? "cols-2" : "")}>
          {q.options.map(opt => (
            <Option key={opt} label={opt} selected={opts.includes(opt)} onClick={() => toggle(opt)} />
          ))}
        </div>
        {q.allowOther && (
          <div>
            <div className="followup-label">Any others not listed:</div>
            <input type="text" value={value?.other || ""} onChange={e => onChange({ ...value, other: e.target.value })} placeholder="e.g. Perplexity, Notion AI" />
          </div>
        )}
      </>
    );
  }

  function LongText({ q, value, onChange }) {
    return (
      <textarea
        value={value?.text || ""}
        onChange={e => onChange({ text: e.target.value })}
        placeholder={q.placeholder || ""}
        style={{ minHeight: 120 }}
      />
    );
  }

  function ToolsTable({ q, value, onChange }) {
    const v = value || {};
    function setCell(tool, col, val) {
      const key = tool + "::" + col;
      const next = { ...v };
      if (next[key] === val) delete next[key]; else next[key] = val;
      onChange(next);
    }
    function cellValue(tool, col) { return v[tool + "::" + col]; }

    return (
      <div className="tools-table">
        <div className="row head">
          <div className="cell">Tool / Platform</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 sel = cellValue(tool, col.id) === opt;
                  const cls = "chip " + (opt === "Yes" ? "yes " : "") + (opt === "No" ? "no " : "") + (sel ? "selected" : "");
                  return (
                    <button key={opt} className={cls} onClick={() => setCell(tool, col.id, opt)}>{opt}</button>
                  );
                })}
              </div>
            ))}
          </div>
        ))}
      </div>
    );
  }

  function Question({ q, value, onChange, num }) {
    return (
      <div className="q-block">
        <div className="q-prompt">
          <span className="qid">{q.id.toUpperCase()}</span>
          {q.prompt}
        </div>
        {q.type === "single" && <SingleChoice q={q} value={value} onChange={onChange} />}
        {q.type === "multi" && <MultiChoice q={q} value={value} onChange={onChange} />}
        {q.type === "longtext" && <LongText q={q} value={value} onChange={onChange} />}
        {q.type === "table" && <ToolsTable q={q} value={value} onChange={onChange} />}
      </div>
    );
  }

  function Sidebar({ sections, currentIdx, onJump, completedMap }) {
    const total = sections.reduce((n,s) => n + s.questions.length, 0);
    const done = Object.values(completedMap).reduce((n,c) => n + c, 0);
    const pct = Math.round((done / total) * 100);
    return (
      <aside className="survey-side">
        <div className="progress-block">
          <div className="label">Your progress</div>
          <div className="pct">{pct}%</div>
          <div className="bar"><div style={{width: pct + "%"}}></div></div>
          <div style={{fontSize:12,color:"var(--muted)",marginTop:8}}>{done} of {total} questions answered</div>
        </div>
        <ol>
          {sections.map((s, i) => {
            const sDone = completedMap[s.id] || 0;
            const sTotal = s.questions.length;
            const cls = i === currentIdx ? "current" : (sDone === sTotal && sTotal > 0 ? "done" : "");
            return (
              <li key={s.id} className={cls} onClick={() => onJump(i)}>
                <span className="num">{i+1}</span>
                <div>
                  <div>{s.title}</div>
                  <div style={{fontSize:11,color:"var(--muted)",marginTop:2}}>{sDone}/{sTotal}</div>
                </div>
              </li>
            );
          })}
        </ol>
      </aside>
    );
  }

  function StandardSurvey({ user, answers, setAnswers, onLogout, onSubmit, onSwitchMode }) {
    const sections = window.SURVEY.sections;
    const [idx, setIdx] = useState(0);
    const section = sections[idx];

    function update(qid, val) {
      setAnswers(prev => ({ ...prev, [qid]: val }));
    }

    function isAnswered(qid) {
      const a = answers[qid];
      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 completedMap = useMemo(() => {
      const m = {};
      for (const s of sections) m[s.id] = s.questions.filter(q => isAnswered(q.id)).length;
      return m;
    }, [answers]);

    const totalQ = sections.reduce((n,s) => n + s.questions.length, 0);
    const doneQ = Object.values(completedMap).reduce((n,c) => n + c, 0);

    return (
      <>
        <Topbar user={user} onLogout={onLogout} crumb={"Standard survey · Section " + (idx+1) + " of " + sections.length} />
        <div className="survey-shell">
          <Sidebar sections={sections} currentIdx={idx} onJump={setIdx} completedMap={completedMap} />
          <main className="survey-main">
            <div className="section-eyebrow">{idx === 0 ? user.name.split(" ")[0] + " \u00b7 Section 1 of " + sections.length : "Section " + (idx+1) + " of " + sections.length}</div>
            <h1 className="section-title">{section.title}</h1>
            <div className="section-blurb">{section.blurb}</div>
            {section.questions.map(q => (
              <Question key={q.id} q={q} value={answers[q.id]} onChange={v => update(q.id, v)} />
            ))}
            <div className="survey-nav">
              <button className="btn ghost" onClick={onSwitchMode}>↺ Switch to chat mode</button>
              <div style={{display:"flex",gap:10}}>
                <button className="btn subtle" onClick={() => setIdx(i => Math.max(0, i-1))} disabled={idx===0}>← Previous</button>
                {idx === sections.length - 1
                  ? <button className="btn primary" onClick={onSubmit}>Review & submit →</button>
                  : <button className="btn primary" onClick={() => { setIdx(i => i+1); window.scrollTo(0,0); }}>Next section →</button>
                }
              </div>
            </div>
            <div style={{textAlign:"center",fontSize:12,color:"var(--muted)",marginTop:24}}>
              {doneQ} of {totalQ} questions answered · saves automatically
            </div>
          </main>
        </div>
      </>
    );
  }

  return StandardSurvey;
})();

window.StandardSurvey = StandardSurvey;
