/* ============================================================
   TechManager — ADMIN CONTENT EDITORS
   (modules, questions, credibility, roadmap, settings)
   ============================================================ */

/* ---- tiny controlled helpers ---- */
const TI = ({ label, value, onChange, placeholder, mono }) => (
  <Field label={label}><input className="input" value={value ?? ''} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} style={mono ? { fontFamily: 'monospace' } : null} /></Field>
);
const TA = ({ label, value, onChange, rows }) => (
  <Field label={label}><textarea className="textarea" rows={rows || 3} value={value ?? ''} onChange={(e) => onChange(e.target.value)} /></Field>
);
const NI = ({ label, value, onChange, min, max, suffix }) => (
  <Field label={label}><div className="center gap-8"><input className="input" type="number" min={min} max={max} value={value} onChange={(e) => onChange(Number(e.target.value))} />{suffix && <span className="muted" style={{ fontSize: 13 }}>{suffix}</span>}</div></Field>
);
const SectionTitle = ({ children, sub }) => (
  <div style={{ marginBottom: 14 }}><div className="field-label" style={{ fontSize: 13.5, color: 'var(--text)' }}>{children}</div>{sub && <div className="dim" style={{ fontSize: 12.5 }}>{sub}</div>}</div>
);
const RowCard = ({ children }) => <div className="card" style={{ padding: 16, background: 'var(--bg-soft)' }}>{children}</div>;

/* =========================================================
   MODULES EDITOR  (videos / text / images / diagrams / Qs)
   ========================================================= */
const BLOCK_TYPES = [
  { type: 'text', label: 'Text / reading', icon: 'book' },
  { type: 'video', label: 'Video', icon: 'play' },
  { type: 'image', label: 'Image', icon: 'image' },
  { type: 'diagram', label: 'Diagram', icon: 'diagram' },
  { type: 'example-question', label: 'Example question', icon: 'target' },
];
const newBlock = (type) => {
  if (type === 'text') return { type, heading: 'Heading', body: 'Write the lesson text here.' };
  if (type === 'video') return { type, title: 'Video title', duration: '5:00' };
  if (type === 'image') return { type, caption: 'Image caption' };
  if (type === 'diagram') return { type, caption: 'Diagram caption', kind: 'flow' };
  return { type: 'example-question', prompt: 'Question prompt?', options: ['Option A', 'Option B', 'Option C'], correct: 0 };
};

const BlockEditor = ({ b, onChange, onDelete, onUp, onDown }) => (
  <RowCard>
    <div className="between" style={{ marginBottom: 10 }}>
      <span className="center gap-8" style={{ fontWeight: 700, fontSize: 13.5 }}>
        <Icon name={BLOCK_TYPES.find((t) => t.type === b.type).icon} size={15} style={{ color: 'var(--blue-2)' }} />
        {BLOCK_TYPES.find((t) => t.type === b.type).label}
      </span>
      <div className="flex gap-8">
        <button className="btn btn-soft btn-sm" onClick={onUp}><Icon name="up" size={14} /></button>
        <button className="btn btn-soft btn-sm" onClick={onDown}><Icon name="down" size={14} /></button>
        <button className="btn btn-danger btn-sm" onClick={onDelete}><Icon name="trash" size={14} /></button>
      </div>
    </div>
    {b.type === 'text' && <><TI label="Heading" value={b.heading} onChange={(v) => onChange({ ...b, heading: v })} /><div className="mt-8" /><TA label="Body" value={b.body} rows={3} onChange={(v) => onChange({ ...b, body: v })} /></>}
    {b.type === 'video' && <div className="grid gap-8" style={{ gridTemplateColumns: '2fr 1fr' }}><TI label="Title" value={b.title} onChange={(v) => onChange({ ...b, title: v })} /><TI label="Duration" value={b.duration} onChange={(v) => onChange({ ...b, duration: v })} /></div>}
    {b.type === 'image' && <TI label="Caption" value={b.caption} onChange={(v) => onChange({ ...b, caption: v })} />}
    {b.type === 'diagram' && <div className="grid gap-8" style={{ gridTemplateColumns: '2fr 1fr' }}><TI label="Caption" value={b.caption} onChange={(v) => onChange({ ...b, caption: v })} /><Field label="Style"><select className="select" value={b.kind} onChange={(e) => onChange({ ...b, kind: e.target.value })}><option value="flow">Flow</option><option value="bars">Bars</option><option value="tree">Tree</option></select></Field></div>}
    {b.type === 'example-question' && <ExampleQEditor b={b} onChange={onChange} />}
  </RowCard>
);

const ExampleQEditor = ({ b, onChange }) => (
  <>
    <TA label="Prompt" value={b.prompt} rows={2} onChange={(v) => onChange({ ...b, prompt: v })} />
    <div className="mt-8" />
    <span className="field-label">Options (select the correct one)</span>
    <div className="grid gap-8">
      {b.options.map((o, i) => (
        <div key={i} className="center gap-8">
          <input type="radio" checked={b.correct === i} onChange={() => onChange({ ...b, correct: i })} style={{ accentColor: 'var(--green)', width: 18, height: 18 }} />
          <input className="input" value={o} onChange={(e) => { const opts = [...b.options]; opts[i] = e.target.value; onChange({ ...b, options: opts }); }} />
          <button className="btn btn-soft btn-sm" onClick={() => { const opts = b.options.filter((_, j) => j !== i); onChange({ ...b, options: opts, correct: Math.min(b.correct, opts.length - 1) }); }}><Icon name="x" size={13} /></button>
        </div>
      ))}
    </div>
    <button className="btn btn-soft btn-sm mt-8" onClick={() => onChange({ ...b, options: [...b.options, 'New option'] })}><Icon name="plus" size={13} /> Add option</button>
  </>
);

const ModulesEditor = ({ draft, update }) => {
  const setModule = (mi, m) => { const modules = [...draft.modules]; modules[mi] = m; update({ ...draft, modules }); };
  const addModule = () => update({ ...draft, modules: [...draft.modules, { id: TM.uid('m'), title: 'New module', summary: 'Module summary', blocks: [] }] });
  const delModule = (mi) => update({ ...draft, modules: draft.modules.filter((_, i) => i !== mi) });
  const move = (arr, i, d) => { const a = [...arr]; const j = i + d; if (j < 0 || j >= a.length) return a; [a[i], a[j]] = [a[j], a[i]]; return a; };
  return (
    <div>
      <SectionTitle sub="Each module holds any mix of videos, text, images, diagrams and example questions.">Study modules ({draft.modules.length})</SectionTitle>
      <div className="grid gap-16">
        {draft.modules.map((m, mi) => (
          <div key={m.id} className="card" style={{ padding: 18 }}>
            <div className="between" style={{ marginBottom: 12 }}>
              <span className="badge badge-draft">Module {mi + 1}</span>
              <div className="flex gap-8">
                <button className="btn btn-soft btn-sm" onClick={() => update({ ...draft, modules: move(draft.modules, mi, -1) })}><Icon name="up" size={14} /></button>
                <button className="btn btn-soft btn-sm" onClick={() => update({ ...draft, modules: move(draft.modules, mi, 1) })}><Icon name="down" size={14} /></button>
                <button className="btn btn-danger btn-sm" onClick={() => delModule(mi)}><Icon name="trash" size={14} /> Module</button>
              </div>
            </div>
            <div className="grid gap-8" style={{ gridTemplateColumns: '1fr 1.4fr' }}>
              <TI label="Title" value={m.title} onChange={(v) => setModule(mi, { ...m, title: v })} />
              <TI label="Summary" value={m.summary} onChange={(v) => setModule(mi, { ...m, summary: v })} />
            </div>
            <div className="mt-16" />
            <span className="field-label">Content blocks</span>
            <div className="grid gap-12">
              {m.blocks.map((b, bi) => (
                <BlockEditor key={bi} b={b}
                  onChange={(nb) => { const blocks = [...m.blocks]; blocks[bi] = nb; setModule(mi, { ...m, blocks }); }}
                  onDelete={() => setModule(mi, { ...m, blocks: m.blocks.filter((_, j) => j !== bi) })}
                  onUp={() => setModule(mi, { ...m, blocks: move(m.blocks, bi, -1) })}
                  onDown={() => setModule(mi, { ...m, blocks: move(m.blocks, bi, 1) })} />
              ))}
            </div>
            <div className="flex gap-8 mt-12" style={{ flexWrap: 'wrap' }}>
              {BLOCK_TYPES.map((t) => (
                <button key={t.type} className="btn btn-soft btn-sm" onClick={() => setModule(mi, { ...m, blocks: [...m.blocks, newBlock(t.type)] })}>
                  <Icon name={t.icon} size={13} /> {t.label}
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>
      <button className="btn btn-ghost mt-16" onClick={addModule}><Icon name="plus" size={15} /> Add module</button>
    </div>
  );
};

/* =========================================================
   QUESTION BANK EDITOR
   ========================================================= */
const QuestionsEditor = ({ draft, update }) => {
  const setQ = (qi, q) => { const questions = [...draft.questions]; questions[qi] = q; update({ ...draft, questions }); };
  const addQ = () => update({ ...draft, questions: [...draft.questions, { id: TM.uid('q'), area: draft.areas[0] || 'General', prompt: 'New question?', options: ['Option A', 'Option B', 'Option C', 'Option D'], correct: 0, explain: '' }] });
  return (
    <div>
      <SectionTitle sub="The exam draws from this bank. Each question maps to a domain so results can compute areas to study. Tag each question with the right domain.">Question bank ({draft.questions.length})</SectionTitle>
      {draft.questions.length > draft.examConfig.numQuestions && <div className="card muted" style={{ padding: '10px 14px', marginBottom: 14, background: 'rgba(47,125,246,0.08)', borderColor: 'rgba(47,125,246,0.25)', fontSize: 13 }}>Exam shows {draft.examConfig.numQuestions} of {draft.questions.length} questions, randomly drawn each attempt.</div>}
      <div className="grid gap-12">
        {draft.questions.map((q, qi) => (
          <RowCard key={q.id}>
            <div className="between" style={{ marginBottom: 10 }}>
              <Field label="Domain"><select className="select" value={q.area} onChange={(e) => setQ(qi, { ...q, area: e.target.value })} style={{ minWidth: 180 }}>{draft.areas.map((a) => <option key={a} value={a}>{a}</option>)}</select></Field>
              <button className="btn btn-danger btn-sm" onClick={() => update({ ...draft, questions: draft.questions.filter((_, i) => i !== qi) })} style={{ alignSelf: 'flex-end' }}><Icon name="trash" size={14} /></button>
            </div>
            <TA label="Prompt" value={q.prompt} rows={2} onChange={(v) => setQ(qi, { ...q, prompt: v })} />
            <div className="mt-8" />
            <span className="field-label">Options (radio marks the correct answer)</span>
            <div className="grid gap-8">
              {q.options.map((o, i) => (
                <div key={i} className="center gap-8">
                  <input type="radio" checked={q.correct === i} onChange={() => setQ(qi, { ...q, correct: i })} style={{ accentColor: 'var(--green)', width: 18, height: 18 }} />
                  <input className="input" value={o} onChange={(e) => { const opts = [...q.options]; opts[i] = e.target.value; setQ(qi, { ...q, options: opts }); }} />
                  <button className="btn btn-soft btn-sm" onClick={() => { const opts = q.options.filter((_, j) => j !== i); setQ(qi, { ...q, options: opts, correct: Math.min(q.correct, opts.length - 1) }); }}><Icon name="x" size={13} /></button>
                </div>
              ))}
            </div>
            <button className="btn btn-soft btn-sm mt-8" onClick={() => setQ(qi, { ...q, options: [...q.options, 'New option'] })}><Icon name="plus" size={13} /> Add option</button>
          </RowCard>
        ))}
      </div>
      <button className="btn btn-ghost mt-16" onClick={addQ}><Icon name="plus" size={15} /> Add question</button>
    </div>
  );
};

/* =========================================================
   CREDIBILITY EDITOR
   ========================================================= */
const CredibilityEditor = ({ db }) => {
  const save = () => TM.saveCredibility(JSON.parse(JSON.stringify(db.credibility)));
  const setEv = (i, e) => { db.credibility.evidence[i] = e; save(); };
  const setFb = (i, f) => { db.credibility.feedback[i] = f; save(); };
  return (
    <div className="grid gap-32">
      <div>
        <div className="between" style={{ marginBottom: 14 }}><SectionTitle sub="The headline stats on the landing page.">Evidence</SectionTitle><button className="btn btn-soft btn-sm" onClick={() => TM.addEvidence()}><Icon name="plus" size={14} /> Add</button></div>
        <div className="grid gap-12">
          {db.credibility.evidence.map((e, i) => (
            <RowCard key={e.id}>
              <div className="between"><div className="grid gap-8" style={{ gridTemplateColumns: '120px 1fr', flex: 1 }}>
                <TI label="Stat" value={e.stat} onChange={(v) => setEv(i, { ...e, stat: v })} />
                <TI label="Label" value={e.label} onChange={(v) => setEv(i, { ...e, label: v })} />
              </div><button className="btn btn-danger btn-sm" style={{ marginLeft: 10, alignSelf: 'flex-end' }} onClick={() => TM.removeEvidence(e.id)}><Icon name="trash" size={14} /></button></div>
              <div className="mt-8" /><TI label="Source" value={e.source} onChange={(v) => setEv(i, { ...e, source: v })} />
            </RowCard>
          ))}
        </div>
      </div>
      <div>
        <div className="between" style={{ marginBottom: 14 }}><SectionTitle sub="Testimonials shown on the landing page.">Feedback</SectionTitle><button className="btn btn-soft btn-sm" onClick={() => TM.addFeedback()}><Icon name="plus" size={14} /> Add</button></div>
        <div className="grid gap-12">
          {db.credibility.feedback.map((f, i) => (
            <RowCard key={f.id}>
              <div className="between" style={{ marginBottom: 8 }}><span className="dim" style={{ fontSize: 12 }}>Testimonial</span><button className="btn btn-danger btn-sm" onClick={() => TM.removeFeedback(f.id)}><Icon name="trash" size={14} /></button></div>
              <TA label="Quote" value={f.quote} rows={2} onChange={(v) => setFb(i, { ...f, quote: v })} />
              <div className="grid gap-8 mt-8" style={{ gridTemplateColumns: '1fr 1fr' }}><TI label="Name" value={f.name} onChange={(v) => setFb(i, { ...f, name: v })} /><TI label="Role" value={f.role} onChange={(v) => setFb(i, { ...f, role: v })} /></div>
            </RowCard>
          ))}
        </div>
      </div>
    </div>
  );
};

/* =========================================================
   ROADMAP EDITOR
   ========================================================= */
const RoadmapEditor = ({ db }) => {
  const items = TM.sortedRoadmap();
  const save = (id, patch) => { const r = db.roadmap.find((x) => x.id === id); Object.assign(r, patch); TM.saveRoadmap(db.roadmap); };
  return (
    <div>
      <div className="between" style={{ marginBottom: 14 }}><SectionTitle sub="Drag order with the arrows. Dates can be exact (e.g. Q3 2026) or just 'coming soon'.">Roadmap milestones</SectionTitle><button className="btn btn-soft btn-sm" onClick={() => TM.addRoadmap()}><Icon name="plus" size={14} /> Add</button></div>
      <div className="grid gap-12">
        {items.map((r, i) => (
          <RowCard key={r.id}>
            <div className="between" style={{ marginBottom: 10 }}>
              <span className="badge badge-draft">#{i + 1}</span>
              <div className="flex gap-8">
                <button className="btn btn-soft btn-sm" disabled={i === 0} onClick={() => TM.moveRoadmap(r.id, -1)}><Icon name="up" size={14} /></button>
                <button className="btn btn-soft btn-sm" disabled={i === items.length - 1} onClick={() => TM.moveRoadmap(r.id, 1)}><Icon name="down" size={14} /></button>
                <button className="btn btn-danger btn-sm" onClick={() => TM.removeRoadmap(r.id)}><Icon name="trash" size={14} /></button>
              </div>
            </div>
            <div className="grid gap-8" style={{ gridTemplateColumns: '1fr 1fr' }}>
              <TI label="Title" value={r.title} onChange={(v) => save(r.id, { title: v })} />
              <Field label="Date type">
                <div className="flex gap-8">
                  <button className={'btn btn-sm ' + (r.exact ? 'btn-primary' : 'btn-soft')} onClick={() => save(r.id, { exact: true })}>Exact date</button>
                  <button className={'btn btn-sm ' + (!r.exact ? 'btn-primary' : 'btn-soft')} onClick={() => save(r.id, { exact: false, date: 'Coming soon' })}>Coming soon</button>
                </div>
              </Field>
            </div>
            <div className="mt-8" />
            <TA label="Description" value={r.description} rows={2} onChange={(v) => save(r.id, { description: v })} />
            {r.exact && <><div className="mt-8" /><TI label="Date label" value={r.date} placeholder="e.g. Q3 2026" onChange={(v) => save(r.id, { date: v })} /></>}
          </RowCard>
        ))}
      </div>
    </div>
  );
};

/* =========================================================
   SETTINGS (stats)
   ========================================================= */
const SettingsEditor = ({ db }) => (
  <div style={{ maxWidth: 520 }}>
    <SectionTitle sub="The base counter that 'Managers certified' starts from. It increments automatically every time someone completes an exam.">Global stats</SectionTitle>
    <div className="card" style={{ padding: 20 }}>
      <NI label="Managers certified — base count" value={db.stats.managersCertifiedBase} onChange={(v) => TM.setStat('managersCertifiedBase', v)} />
      <div className="muted" style={{ fontSize: 13, margin: '10px 0 18px' }}>Live total displayed: <strong style={{ color: 'var(--text)' }}>{TM.managersCertified().toLocaleString()}</strong> (base {db.stats.managersCertifiedBase.toLocaleString()} + {db.user.attempts.length} exam{db.user.attempts.length === 1 ? '' : 's'} taken)</div>
      <div className="grid gap-8" style={{ gridTemplateColumns: '1fr 1fr' }}>
        <NI label="Price — low" value={db.stats.pricePerCertLow} suffix="$" onChange={(v) => TM.setStat('pricePerCertLow', v)} />
        <NI label="Price — high" value={db.stats.pricePerCertHigh} suffix="$" onChange={(v) => TM.setStat('pricePerCertHigh', v)} />
      </div>
    </div>
    <div className="card" style={{ padding: 20, marginTop: 20 }}>
      <SectionTitle sub="Domains covered is computed automatically as the number of visible certifications (Ready + Coming soon).">Computed values</SectionTitle>
      <div className="between" style={{ fontSize: 14 }}><span className="muted">Domains covered</span><strong>{TM.domainsCovered()}</strong></div>
      <div className="between mt-8" style={{ fontSize: 14 }}><span className="muted">Ready certifications</span><strong>{TM.readyCerts().length}</strong></div>
    </div>
    <div className="card" style={{ padding: 20, marginTop: 20, borderColor: 'rgba(248,113,113,0.25)' }}>
      <SectionTitle sub="Wipe all local data and restore the seed database.">Danger zone</SectionTitle>
      <button className="btn btn-danger" onClick={() => { if (confirm('Reset all data to seed defaults? This clears exam attempts and edits.')) TM.reset(); }}><Icon name="refresh" size={15} /> Reset to seed data</button>
    </div>
  </div>
);

Object.assign(window, { TI, TA, NI, SectionTitle, RowCard, BLOCK_TYPES, newBlock, BlockEditor, ExampleQEditor, ModulesEditor, QuestionsEditor, CredibilityEditor, RoadmapEditor, SettingsEditor });
