/* ============================================================
   TechManager — ADMIN PANEL (shell + cert editor + network)
   ============================================================ */

const STATUS_OPTS = [
  { v: 'READY', label: 'Ready', hint: 'Public + exam open' },
  { v: 'COMING_SOON', label: 'Coming soon', hint: 'Visible, exam locked' },
  { v: 'NOT_READY', label: 'Not ready', hint: 'Hidden everywhere' },
];
const SWATCHES = [['#2b8cff', '#1e63d8'], ['#ff6a3d', '#e8431f'], ['#c64be8', '#8b2fd6'], ['#6b6bf5', '#4f3fe0'], ['#2dd4bf', '#0e9488'], ['#f5c451', '#d39a14'], ['#34d399', '#0e9488'], ['#fb7185', '#e11d48']];

/* ---- Cert editor (sub-tabbed) ---- */
const CertEditor = ({ cert, onClose }) => {
  const [draft, setDraft] = useState(() => JSON.parse(JSON.stringify(cert)));
  const [tab, setTab] = useState('basics');
  const set = (patch) => setDraft((d) => ({ ...d, ...patch }));
  const save = () => { TM.saveCert(JSON.parse(JSON.stringify(draft))); onClose(); };

  const tabs = [['basics', 'Basics'], ['domains', 'Domains'], ['exam', 'Exam config'], ['modules', 'Modules'], ['questions', 'Questions']];

  return (
    <div className="fadein">
      <div className="between" style={{ marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
        <button className="btn btn-soft btn-sm" onClick={onClose}><Icon name="arrowL" size={15} /> All certifications</button>
        <div className="flex gap-12">
          <button className="btn btn-soft" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" onClick={save}><Icon name="check" size={15} /> Save changes</button>
        </div>
      </div>

      <div className="center gap-16" style={{ marginBottom: 20 }}>
        <Orb cert={draft} size={56} />
        <div><h2 className="display" style={{ fontSize: 24 }}>{draft.name || 'Untitled'}</h2><StatusBadge status={draft.status} /></div>
      </div>

      {/* sub tabs */}
      <div className="flex gap-8" style={{ borderBottom: '1px solid var(--border)', marginBottom: 22, flexWrap: 'wrap' }}>
        {tabs.map(([k, l]) => (
          <button key={k} className="nav-link" onClick={() => setTab(k)} style={{ borderRadius: 0, borderBottom: '2px solid ' + (tab === k ? 'var(--blue)' : 'transparent'), color: tab === k ? '#fff' : 'var(--muted)', background: 'none' }}>{l}</button>
        ))}
      </div>

      {tab === 'basics' && (
        <div style={{ maxWidth: 720 }} className="grid gap-16">
          <div className="grid gap-12" style={{ gridTemplateColumns: '1fr 120px' }}>
            <TI label="Certification name" value={draft.name} onChange={(v) => set({ name: v })} />
            <TI label="Emoji" value={draft.emoji} onChange={(v) => set({ emoji: v })} />
          </div>
          <TI label="Tagline" value={draft.tagline} onChange={(v) => set({ tagline: v })} />
          <TA label="Description" value={draft.description} rows={3} onChange={(v) => set({ description: v })} />
          <div className="grid gap-12" style={{ gridTemplateColumns: '1fr 160px' }}>
            <Field label="Status">
              <div className="grid gap-8" style={{ gridTemplateColumns: 'repeat(3,1fr)' }}>
                {STATUS_OPTS.map((s) => (
                  <button key={s.v} onClick={() => set({ status: s.v })} className="card" style={{ padding: '10px 8px', textAlign: 'center', cursor: 'pointer', borderColor: draft.status === s.v ? 'var(--blue)' : 'var(--border)', background: draft.status === s.v ? 'rgba(47,125,246,0.1)' : 'var(--bg-soft)' }}>
                    <div style={{ fontWeight: 700, fontSize: 13.5 }}>{s.label}</div>
                    <div className="dim" style={{ fontSize: 11, marginTop: 2 }}>{s.hint}</div>
                  </button>
                ))}
              </div>
            </Field>
            <NI label="Price" value={draft.price} suffix="$" onChange={(v) => set({ price: v })} />
          </div>
          <Field label="Orb color">
            <div className="flex gap-8" style={{ flexWrap: 'wrap' }}>
              {SWATCHES.map(([a, b]) => (
                <button key={a} onClick={() => set({ color: a, color2: b })} style={{ width: 38, height: 38, borderRadius: 10, border: draft.color === a ? '2px solid #fff' : '2px solid transparent', background: `radial-gradient(circle at 35% 30%, ${lighten(a)}, ${a} 55%, ${b})`, cursor: 'pointer' }} />
              ))}
            </div>
          </Field>
        </div>
      )}

      {tab === 'domains' && (
        <div style={{ maxWidth: 620 }}>
          <SectionTitle sub="Domains are the areas a question can belong to. Results show the user's score per domain. 'Domains covered' on the site counts visible certifications.">Domains / knowledge areas ({draft.areas.length})</SectionTitle>
          <div className="grid gap-8">
            {draft.areas.map((a, i) => (
              <div key={i} className="center gap-8">
                <input className="input" value={a} onChange={(e) => { const areas = [...draft.areas]; areas[i] = e.target.value; set({ areas }); }} />
                <button className="btn btn-soft btn-sm" onClick={() => set({ areas: draft.areas.filter((_, j) => j !== i) })}><Icon name="x" size={14} /></button>
              </div>
            ))}
          </div>
          <button className="btn btn-soft btn-sm mt-12" onClick={() => set({ areas: [...draft.areas, 'New domain'] })}><Icon name="plus" size={13} /> Add domain</button>
        </div>
      )}

      {tab === 'exam' && (
        <div style={{ maxWidth: 560 }}>
          <SectionTitle sub="The exam engine reads these. Questions are drawn from the bank; password is verified before the exam starts.">Exam configuration</SectionTitle>
          <div className="card grid gap-16" style={{ padding: 22 }}>
            <div className="grid gap-12" style={{ gridTemplateColumns: '1fr 1fr 1fr' }}>
              <NI label="Questions" value={draft.examConfig.numQuestions} min={1} max={draft.questions.length || 1} onChange={(v) => set({ examConfig: { ...draft.examConfig, numQuestions: v } })} />
              <NI label="Time" suffix="min" value={draft.examConfig.timeMinutes} min={1} onChange={(v) => set({ examConfig: { ...draft.examConfig, timeMinutes: v } })} />
              <NI label="Pass grade" suffix="%" value={draft.examConfig.passGrade} min={1} max={100} onChange={(v) => set({ examConfig: { ...draft.examConfig, passGrade: v } })} />
            </div>
            <TI label="Exam access password" mono value={draft.examConfig.password} onChange={(v) => set({ examConfig: { ...draft.examConfig, password: v } })} />
            <div className="muted" style={{ fontSize: 13 }}>Bank has <strong style={{ color: 'var(--text)' }}>{draft.questions.length}</strong> questions. The exam shows {Math.min(draft.examConfig.numQuestions, draft.questions.length)} per attempt.</div>
          </div>
        </div>
      )}

      {tab === 'modules' && <ModulesEditor draft={draft} update={setDraft} />}
      {tab === 'questions' && <QuestionsEditor draft={draft} update={setDraft} />}

      <div className="between mt-32" style={{ paddingTop: 18, borderTop: '1px solid var(--border)' }}>
        <button className="btn btn-soft" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={save}><Icon name="check" size={15} /> Save changes</button>
      </div>
    </div>
  );
};

/* ---- Network / graph editor (drag + connections) ---- */
const NetworkEditor = ({ db }) => {
  const [selId, setSelId] = useState(db.certifications[0] && db.certifications[0].id);
  const ref = useRef();
  const dragRef = useRef(null);
  const sel = db.certifications.find((c) => c.id === selId);

  const onDown = (c) => (e) => { e.preventDefault(); setSelId(c.id); dragRef.current = c.id; };
  useEffect(() => {
    const move = (e) => {
      if (!dragRef.current || !ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const x = Math.max(4, Math.min(96, ((e.clientX - r.left) / r.width) * 100));
      const y = Math.max(4, Math.min(96, ((e.clientY - r.top) / r.height) * 100));
      const c = db.certifications.find((cc) => cc.id === dragRef.current);
      c.x = Math.round(x); c.y = Math.round(y);
      TM.saveCert(c);
    };
    const up = () => { dragRef.current = null; };
    window.addEventListener('mousemove', move); window.addEventListener('mouseup', up);
    return () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); };
  }, [db]);

  return (
    <div>
      <SectionTitle sub="Drag the orbs to position them. Select one, then toggle which certifications it links to. This is exactly what renders on the homepage and catalog.">Network graph</SectionTitle>
      <div className="grid gap-20" style={{ gridTemplateColumns: '1.4fr 1fr', alignItems: 'start' }}>
        <div className="card" style={{ padding: 16 }}>
          <div ref={ref} className="graph" style={{ aspectRatio: '1/0.8', cursor: 'grab' }}>
            <svg preserveAspectRatio="none">
              {db.certifications.flatMap((c) => (c.connections || []).map((tid) => {
                const t = db.certifications.find((x) => x.id === tid); if (!t || c.id > tid) return null;
                return <line key={c.id + tid} x1={c.x + '%'} y1={c.y + '%'} x2={t.x + '%'} y2={t.y + '%'} stroke="var(--blue)" strokeWidth="2" opacity="0.8" />;
              }))}
            </svg>
            {db.certifications.map((c) => (
              <div key={c.id} className="node" style={{ left: c.x + '%', top: c.y + '%', cursor: 'grab' }} onMouseDown={onDown(c)}>
                <div style={{ outline: selId === c.id ? '3px solid var(--blue-2)' : 'none', outlineOffset: 4, borderRadius: '50%' }}>
                  <Orb cert={c} size={58} dim={c.status === 'NOT_READY'} />
                </div>
                <div className="node-label" style={{ fontSize: 11 }}>{c.name.replace(' Manager', '')}</div>
              </div>
            ))}
          </div>
          <p className="dim" style={{ fontSize: 12, textAlign: 'center', marginTop: 8 }}>Tip: drag orbs to reposition · positions save live</p>
        </div>

        <div className="card" style={{ padding: 18 }}>
          {sel ? (
            <>
              <div className="center gap-12" style={{ marginBottom: 14 }}><Orb cert={sel} size={40} /><div><div style={{ fontWeight: 700 }}>{sel.name}</div><StatusBadge status={sel.status} /></div></div>
              <span className="field-label">Connects to</span>
              <div className="grid gap-8">
                {db.certifications.filter((c) => c.id !== sel.id).map((c) => {
                  const on = (sel.connections || []).includes(c.id);
                  return (
                    <button key={c.id} onClick={() => TM.toggleConnection(sel.id, c.id)} className="between" style={{ padding: '9px 12px', borderRadius: 10, border: '1px solid ' + (on ? 'var(--blue)' : 'var(--border-strong)'), background: on ? 'rgba(47,125,246,0.1)' : 'var(--bg-soft)', cursor: 'pointer' }}>
                      <span className="center gap-8" style={{ fontSize: 13.5, color: 'var(--text)' }}><Orb cert={c} size={22} /> {c.name.replace(' Manager', '')}</span>
                      <span style={{ width: 20, height: 20, borderRadius: 6, border: '1px solid ' + (on ? 'var(--blue)' : 'var(--dim)'), background: on ? 'var(--blue)' : 'transparent', display: 'grid', placeItems: 'center' }}>{on && <Icon name="check" size={13} style={{ color: '#fff' }} />}</span>
                    </button>
                  );
                })}
              </div>
              <div className="grid gap-8 mt-16" style={{ gridTemplateColumns: '1fr 1fr' }}>
                <NI label="X %" value={sel.x} min={0} max={100} onChange={(v) => { sel.x = v; TM.saveCert(sel); }} />
                <NI label="Y %" value={sel.y} min={0} max={100} onChange={(v) => { sel.y = v; TM.saveCert(sel); }} />
              </div>
            </>
          ) : <span className="muted">Select a certification.</span>}
        </div>
      </div>
    </div>
  );
};

/* ---- Certifications list ---- */
const CertsList = ({ db, onEdit }) => (
  <div>
    <div className="between" style={{ marginBottom: 16 }}>
      <SectionTitle sub="Every certification, including hidden drafts. Status controls where each one appears.">Certifications ({db.certifications.length})</SectionTitle>
      <button className="btn btn-primary btn-sm" onClick={() => onEdit(TM.addCert())}><Icon name="plus" size={15} /> New certification</button>
    </div>
    <div className="grid gap-12">
      {db.certifications.map((c) => (
        <div key={c.id} className="card between" style={{ padding: '14px 18px' }}>
          <div className="center gap-16">
            <Orb cert={c} size={44} dim={c.status === 'NOT_READY'} />
            <div>
              <div className="center gap-8"><span style={{ fontWeight: 700 }}>{c.name}</span><StatusBadge status={c.status} /></div>
              <div className="dim" style={{ fontSize: 12.5, marginTop: 2 }}>{c.modules.length} modules · {c.questions.length} questions · {c.areas.length} domains · pass {c.examConfig.passGrade}%</div>
            </div>
          </div>
          <div className="flex gap-8">
            <button className="btn btn-soft btn-sm" onClick={() => onEdit(c)}><Icon name="edit" size={14} /> Edit</button>
            <button className="btn btn-danger btn-sm" onClick={() => { if (confirm('Delete ' + c.name + '?')) TM.deleteCert(c.id); }}><Icon name="trash" size={14} /></button>
          </div>
        </div>
      ))}
    </div>
  </div>
);

/* ---- Admin shell ---- */
const AdminPanel = ({ db, go }) => {
  const [tab, setTab] = useState('certs');
  const [editing, setEditing] = useState(null); // cert being edited

  const tabs = [['certs', 'Certifications', 'grid'], ['network', 'Network', 'share'], ['credibility', 'Credibility', 'award'], ['roadmap', 'Roadmap', 'clock'], ['settings', 'Settings', 'settings']];

  return (
    <div className="fadein wrap section tight">
      <div className="between" style={{ marginBottom: 8, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div className="eyebrow">Admin panel</div>
          <h1 className="display" style={{ fontSize: 'clamp(28px,3.4vw,42px)', marginTop: 10 }}>Control everything</h1>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => go('home')}>View site <Icon name="arrow" size={14} /></button>
      </div>
      <p className="muted" style={{ marginTop: 0, marginBottom: 26 }}>This is the source of truth. Every edit here flows live to the public site, learning paths, exams and profiles.</p>

      {editing ? (
        <div className="card" style={{ padding: 26 }}><CertEditor cert={editing} onClose={() => setEditing(null)} /></div>
      ) : (
        <>
          <div className="flex gap-8" style={{ marginBottom: 26, flexWrap: 'wrap' }}>
            {tabs.map(([k, l, ic]) => (
              <button key={k} className={'btn btn-sm ' + (tab === k ? 'btn-primary' : 'btn-soft')} onClick={() => setTab(k)}><Icon name={ic} size={14} /> {l}</button>
            ))}
          </div>
          {tab === 'certs' && <CertsList db={db} onEdit={setEditing} />}
          {tab === 'network' && <NetworkEditor db={db} />}
          {tab === 'credibility' && <CredibilityEditor db={db} />}
          {tab === 'roadmap' && <RoadmapEditor db={db} />}
          {tab === 'settings' && <SettingsEditor db={db} />}
        </>
      )}
    </div>
  );
};

Object.assign(window, { CertEditor, NetworkEditor, CertsList, AdminPanel });
