/* ELEV8 ATS - Config surfaces: custom Fields (record schema) and pipeline Stages. */

const DScfg = window.Stand8DesignSystem_b5c975;

/* ============================== FIELDS ============================== */
const FIELD_TYPE_META = {
  text: { icon: 'text_fields', label: 'Text' },
  textarea: { icon: 'notes', label: 'Long text' },
  number: { icon: 'tag', label: 'Number' },
  currency: { icon: 'payments', label: 'Currency' },
  select: { icon: 'arrow_drop_down_circle', label: 'Dropdown' },
  multiselect: { icon: 'checklist', label: 'Multi-select' },
  date: { icon: 'calendar_today', label: 'Date' },
  boolean: { icon: 'toggle_on', label: 'Toggle' },
  email: { icon: 'alternate_email', label: 'Email' },
  phone: { icon: 'call', label: 'Phone' },
  url: { icon: 'link', label: 'URL' },
  user: { icon: 'person', label: 'User' },
  rating: { icon: 'star', label: 'Rating' },
};
const SOURCE_META = {
  standard: { label: 'Standard', tone: 'neutral' },
  custom: { label: 'Custom', tone: 'accent' },
  ai: { label: 'AI-derived', tone: 'info' },
  bullhorn: { label: 'Bullhorn', tone: 'neutral' },
  zoominfo: { label: 'ZoomInfo', tone: 'neutral' },
};
const FIELD_TYPES = Object.keys(FIELD_TYPE_META);

function TypeCell({ type }) {
  const t = FIELD_TYPE_META[type] || FIELD_TYPE_META.text;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)' }}>
      <span className="material-symbols-outlined" style={{ fontSize: 15, color: 'var(--ui-text-tertiary)' }}>{t.icon}</span>{t.label}
    </span>
  );
}

function AddFieldDialog({ object, onAdd, onClose, seed }) {
  const [label, setLabel] = React.useState(seed ? seed.label : '');
  const [type, setType] = React.useState(seed ? seed.type : 'text');
  const [required, setRequired] = React.useState(false);
  const [options, setOptions] = React.useState('');
  const canAdd = label.trim().length > 0;
  const submit = () => {
    if (!canAdd) return;
    const key = label.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
    onAdd({ label: label.trim(), key, type, source: 'custom', required, coverage: 0, options: (type === 'select' || type === 'multiselect') && options.trim() ? options.split(',').map((s) => s.trim()).filter(Boolean) : undefined });
  };
  return (
    <DScfg.Modal title={'New ' + object + ' field'} ariaLabel="Add field" closeTitle="Cancel" onClose={onClose} style={{ width: 480 }}>
        <div style={{ padding: '14px 16px', display: 'grid', gap: 14 }}>
          <div>
            <div className="e8-sectionlabel" style={{ marginBottom: 6 }}>Field label</div>
            <DScfg.Input value={label} autoFocus placeholder="e.g. Visa expiry date" onChange={(e) => setLabel(e.target ? e.target.value : e)} />
          </div>
          <div>
            <div className="e8-sectionlabel" style={{ marginBottom: 6 }}>Type</div>
            <div className="e8-cfg-typegrid">
              {FIELD_TYPES.map((t) => (
                <button key={t} type="button" className={'e8-cfg-typebtn' + (type === t ? ' on' : '')} onClick={() => setType(t)}>
                  <span className="material-symbols-outlined" style={{ fontSize: 16 }}>{FIELD_TYPE_META[t].icon}</span>
                  {FIELD_TYPE_META[t].label}
                </button>
              ))}
            </div>
          </div>
          {type === 'select' || type === 'multiselect' ? (
            <div>
              <div className="e8-sectionlabel" style={{ marginBottom: 6 }}>Options <span style={{ fontWeight: 400, color: 'var(--ui-text-tertiary)' }}>· comma-separated</span></div>
              <DScfg.Input value={options} placeholder="Option A, Option B, Option C" onChange={(e) => setOptions(e.target ? e.target.value : e)} />
            </div>
          ) : null}
          <label className="e8-cfg-reqrow">
            <span><b>Required</b><br /><span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>Block save until this field is filled</span></span>
            <DScfg.Toggle checked={required} onChange={() => setRequired(!required)} />
          </label>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', flex: 1 }}>Added as a custom field · syncs to Bullhorn on save.</span>
            <DScfg.Button variant="ghost" size="sm" onClick={onClose}>Cancel</DScfg.Button>
            <DScfg.Button variant="primary" size="sm" icon="add" disabled={!canAdd} onClick={submit}>Add field</DScfg.Button>
          </div>
        </div>
    </DScfg.Modal>
  );
}

function FieldsScreen() {
  const D = window.E8DATA;
  const { showToast, density } = React.useContext(window.E8Ctx);
  const [schema, setSchema] = React.useState(() => {
    try { const s = JSON.parse(localStorage.getItem('e8-fields-v1')); if (s) return s; } catch (e) {}
    return JSON.parse(JSON.stringify(D.fieldSchema));
  });
  React.useEffect(() => { try { localStorage.setItem('e8-fields-v1', JSON.stringify(schema)); } catch (e) {} window.E8DATA.fieldSchema = schema; }, [schema]);
  const objects = Object.keys(schema);
  const [obj, setObj] = React.useState(objects[0]);
  const [addOpen, setAddOpen] = React.useState(false);
  const [seed, setSeed] = React.useState(null);

  const cur = schema[obj];
  const fields = cur.fields;
  const custom = fields.filter((f) => f.source === 'custom').length;
  const aiCount = fields.filter((f) => f.source === 'ai').length;
  const avgCov = Math.round(fields.reduce((n, f) => n + f.coverage, 0) / fields.length);
  const suggestions = D.suggestedFields[obj] || [];

  const { confirm, dialog } = window.useConfirm();
  const setFields = (next) => setSchema({ ...schema, [obj]: { ...cur, fields: next } });
  const toggleReq = (key) => setFields(fields.map((f) => (f.key === key ? { ...f, required: !f.required } : f)));
  const removeField = (key) => setFields(fields.filter((f) => f.key !== key));
  const confirmRemoveField = (f) => confirm({
    title: 'Delete “' + f.label + '”?',
    body: 'This removes the field from all ' + cur.label + ' records. Data already collected for it will no longer be shown.',
    confirmLabel: 'Delete field',
    onConfirm: () => { const prev = fields; removeField(f.key); showToast('“' + f.label + '” deleted', 'Undo', () => setFields(prev)); },
  });
  const addField = (f) => { setFields([...fields, f]); setAddOpen(false); setSeed(null); showToast('Added “' + f.label + '” to ' + cur.label + ' records'); };
  const addSuggested = (s) => { const key = s.label.toLowerCase().replace(/[^a-z0-9]+/g, '_'); setFields([...fields, { label: s.label, key, type: s.type, source: 'custom', coverage: 0 }]); showToast('Added “' + s.label + '” - ELEV8 will start collecting it'); };

  return (
    <React.Fragment>
      <Topbar
        crumbs={[{ label: 'Fields' }]}
        actions={
          <React.Fragment>
            <DScfg.Button variant="secondary" size="sm" icon="upload">Export schema</DScfg.Button>
            <DScfg.Button variant="primary" size="sm" icon="add" onClick={() => { setSeed(null); setAddOpen(true); }}>New field</DScfg.Button>
          </React.Fragment>
        }
      />
      <div className="e8-content">
        <div className="e8-page">
          <div className="e8-pagehead">
            <div>
              <h1 className="e8-h1">Fields</h1>
              <div className="e8-pagehead-sub">Customize the data captured on every record - standard, custom, synced and AI-derived</div>
            </div>
          </div>

          {/* Object tabs */}
          <div style={{ margin: '4px 0 14px' }}>
            <DScfg.SubTabs
              items={objects.map((o) => ({ id: o, label: schema[o].label, count: schema[o].fields.length }))}
              active={obj}
              onChange={setObj}
            />
          </div>

          {/* Stat band */}
          <div className="e8-cfg-stats">
            {[['Fields', String(fields.length)], ['Custom', String(custom)], ['AI-derived', String(aiCount)], ['Avg coverage', avgCov + '%']].map(([k, v]) => (
              <div key={k} className="e8-cfg-stat"><div className="e8-cfg-stat-k">{k}</div><div className="e8-cfg-stat-v tnum">{v}</div></div>
            ))}
          </div>

          {/* Suggested fields */}
          {suggestions.length ? (
            <div className="e8-card e8-aibrief" style={{ margin: '0 0 16px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <span className="material-symbols-outlined" style={{ fontSize: 16, color: 'var(--ui-daybreak-text)' }}>auto_awesome</span>
                <span className="e8-sectionlabel">Suggested fields</span>
                <DScfg.ProvenanceBadge kind="advised" />
              </div>
              <div className="e8-cfg-sugg">
                {suggestions.map((s) => (
                  <div key={s.label} className="e8-cfg-sugg-item">
                    <span className="material-symbols-outlined" style={{ fontSize: 16, color: 'var(--ui-text-tertiary)' }}>{(FIELD_TYPE_META[s.type] || FIELD_TYPE_META.text).icon}</span>
                    <span style={{ minWidth: 0, flex: 1 }}>
                      <span style={{ display: 'block', fontSize: 'var(--ui-text-base)', fontWeight: 500 }}>{s.label}</span>
                      <span style={{ display: 'block', fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>{s.reason}</span>
                    </span>
                    <DScfg.Button variant="secondary" size="sm" icon="add" onClick={() => addSuggested(s)}>Add</DScfg.Button>
                  </div>
                ))}
              </div>
            </div>
          ) : null}

          {/* Field table */}
          <ConfigurableTable listKey="config-fields"
            density={density}
            registry={[
              { key: 'label', label: 'Field', render: (f) => (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9 }}>
                  <span className="material-symbols-outlined" style={{ fontSize: 16, color: 'var(--ui-text-tertiary)' }}>{(FIELD_TYPE_META[f.type] || FIELD_TYPE_META.text).icon}</span>
                  <span style={{ minWidth: 0 }}>
                    <span style={{ display: 'block', fontWeight: 500 }}>{f.label}</span>
                    <span className="e8-cfg-key">{f.key}{f.options ? ' · ' + f.options.length + ' options' : ''}</span>
                  </span>
                </span>
              ) },
              { key: 'type', label: 'Type', render: (f) => <TypeCell type={f.type} /> },
              { key: 'source', label: 'Source', render: (f) => (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <DScfg.Badge tone={(SOURCE_META[f.source] || SOURCE_META.standard).tone}>{(SOURCE_META[f.source] || SOURCE_META.standard).label}</DScfg.Badge>
                  {f.source === 'ai' ? <DScfg.ProvenanceBadge kind="computed" /> : null}
                </span>
              ) },
              { key: 'required', label: 'Required', render: (f) => <DScfg.Toggle checked={!!f.required} onChange={() => toggleReq(f.key)} /> },
              { key: 'coverage', label: 'Coverage', width: 160, render: (f) => (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 64, display: 'inline-flex' }}><DScfg.Progress value={f.coverage} soft={f.coverage < 60} /></span>
                  <span className="tnum" style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>{f.coverage}%</span>
                </span>
              ) },
            ]}
            rows={fields.map((f) => ({ ...f, id: f.key }))}
            rowActions={(f) => (
              <DScfg.MenuButton
                items={[
                  { icon: 'edit', label: 'Edit field', onClick: () => showToast('Field editor opens here') },
                  { icon: 'visibility', label: 'Hide on forms', onClick: () => showToast(f.label + ' hidden on forms') },
                  { separator: true },
                  { icon: 'delete', label: 'Delete field', danger: true, disabled: f.source === 'standard', onClick: () => confirmRemoveField(f) },
                ]}
              />
            )}
          />
          <div className="e8-listfoot">{fields.length} fields on {cur.label} · {custom} custom · synced with Bullhorn 24 min ago</div>
        </div>
      </div>
      {addOpen ? <AddFieldDialog object={cur.label} seed={seed} onAdd={addField} onClose={() => { setAddOpen(false); setSeed(null); }} /> : null}
      {dialog}
    </React.Fragment>
  );
}

/* ============================== STAGES ============================== */
const STAGE_CAT = {
  open: { label: 'In progress', tone: 'neutral', color: 'var(--ui-accent)' },
  won: { label: 'Won', tone: 'success', color: 'var(--ui-success)' },
  lost: { label: 'Lost', tone: 'danger', color: 'var(--ui-text-tertiary)' },
};

function AddStageDialog({ onAdd, onClose }) {
  const [name, setName] = React.useState('');
  const [category, setCategory] = React.useState('open');
  const [sla, setSla] = React.useState(3);
  const [autos, setAutos] = React.useState('');
  const canAdd = name.trim().length > 0;
  const submit = () => {
    if (!canAdd) return;
    onAdd({ name: name.trim(), key: name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_'), abbrev: name.trim().slice(0, 6), category, slaDays: category === 'open' ? sla : 0, conversion: category === 'open' ? 50 : null, count: 0, automations: autos.trim() ? autos.split(',').map((s) => s.trim()).filter(Boolean) : [], description: '' });
  };
  return (
    <DScfg.Modal title="New stage" ariaLabel="Add stage" closeTitle="Cancel" onClose={onClose} style={{ width: 480 }}>
        <div style={{ padding: '14px 16px', display: 'grid', gap: 14 }}>
          <div>
            <div className="e8-sectionlabel" style={{ marginBottom: 6 }}>Stage name</div>
            <DScfg.Input value={name} autoFocus placeholder="e.g. Reference check" onChange={(e) => setName(e.target ? e.target.value : e)} />
          </div>
          <div>
            <div className="e8-sectionlabel" style={{ marginBottom: 6 }}>Category</div>
            <div style={{ display: 'flex', gap: 6 }}>
              {Object.keys(STAGE_CAT).map((c) => (
                <button key={c} type="button" className={'e8-reason-chip' + (category === c ? ' on' : '')} onClick={() => setCategory(c)}>{STAGE_CAT[c].label}</button>
              ))}
            </div>
          </div>
          {category === 'open' ? (
            <div>
              <div className="e8-sectionlabel" style={{ marginBottom: 6 }}>SLA target (days)</div>
              <div className="e8-cfg-stepper">
                <button type="button" onClick={() => setSla(Math.max(1, sla - 1))}><span className="material-symbols-outlined" style={{ fontSize: 16 }}>remove</span></button>
                <span className="tnum">{sla}</span>
                <button type="button" onClick={() => setSla(sla + 1)}><span className="material-symbols-outlined" style={{ fontSize: 16 }}>add</span></button>
              </div>
            </div>
          ) : null}
          <div>
            <div className="e8-sectionlabel" style={{ marginBottom: 6 }}>Automations on enter <span style={{ fontWeight: 400, color: 'var(--ui-text-tertiary)' }}>· comma-separated</span></div>
            <DScfg.Input value={autos} placeholder="Notify recruiter, Draft email" onChange={(e) => setAutos(e.target ? e.target.value : e)} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', flex: 1 }}>Added to the end of the pipeline · drag to reposition.</span>
            <DScfg.Button variant="ghost" size="sm" onClick={onClose}>Cancel</DScfg.Button>
            <DScfg.Button variant="primary" size="sm" icon="add" disabled={!canAdd} onClick={submit}>Add stage</DScfg.Button>
          </div>
        </div>
    </DScfg.Modal>
  );
}

/* Horizontal flow viz: stage cards with conversion arrows between them.
   Classes are .e8-stagemap-* - .e8-stageflow belongs to the DS StageFlow component
   (components/ats-stages), whose injected rules collided with this local block. */
function StageFlow({ stages }) {
  return (
    <div className="e8-stagemap">
      {stages.map((s, i) => (
        <React.Fragment key={s.key}>
          <div className={'e8-stagemap-node is-' + s.category}>
            <div className="e8-stagemap-count tnum">{s.count}</div>
            <div className="e8-stagemap-name">{s.name}</div>
            {s.category !== 'open' ? <span className="e8-stagemap-tag">{STAGE_CAT[s.category].label}</span> : <span className="e8-stagemap-sla">{s.slaDays}d SLA</span>}
          </div>
          {i < stages.length - 1 && s.conversion != null ? (
            <div className="e8-stagemap-arrow">
              <span className="tnum">{s.conversion}%</span>
              <span className="material-symbols-outlined">arrow_forward</span>
            </div>
          ) : (i < stages.length - 1 ? <div className="e8-stagemap-gap"></div> : null)}
        </React.Fragment>
      ))}
    </div>
  );
}

function StagesScreen() {
  const D = window.E8DATA;
  const { showToast } = React.useContext(window.E8Ctx);
  const [pipes, setPipes] = React.useState(() => JSON.parse(JSON.stringify(D.stagePipelines)));
  const [pid, setPid] = React.useState(pipes[0].id);
  const [addOpen, setAddOpen] = React.useState(false);

  const pipe = pipes.find((p) => p.id === pid);
  const stages = pipe.stages;
  const openStages = stages.filter((s) => s.category === 'open');
  const totalAutos = stages.reduce((n, s) => n + s.automations.length, 0);
  const avgSla = openStages.length ? Math.round(openStages.reduce((n, s) => n + s.slaDays, 0) / openStages.length) : 0;
  const inFlight = openStages.reduce((n, s) => n + s.count, 0);

  const setStages = (next) => setPipes(pipes.map((p) => (p.id === pid ? { ...p, stages: next } : p)));
  const move = (i, dir) => {
    const j = i + dir;
    if (j < 0 || j >= stages.length) return;
    const next = stages.slice();
    const tmp = next[i]; next[i] = next[j]; next[j] = tmp;
    setStages(next);
  };
  const setSla = (key, v) => setStages(stages.map((s) => (s.key === key ? { ...s, slaDays: Math.max(1, v) } : s)));
  const removeAuto = (key, a) => setStages(stages.map((s) => (s.key === key ? { ...s, automations: s.automations.filter((x) => x !== a) } : s)));
  const removeStage = (key) => setStages(stages.filter((s) => s.key !== key));
  const { confirm, dialog } = window.useConfirm();
  const confirmRemoveStage = (s) => confirm({
    title: 'Delete the “' + s.name + '” stage?',
    body: (s.count ? s.count + ' record' + (s.count === 1 ? '' : 's') + ' currently sit in this stage. ' : '') + 'Removing it changes the pipeline for everyone on ' + pipe.label + '.',
    confirmLabel: 'Delete stage',
    onConfirm: () => { const prev = stages; removeStage(s.key); showToast('“' + s.name + '” stage deleted', 'Undo', () => setStages(prev)); },
  });
  const addStage = (s) => { setStages([...stages, s]); setAddOpen(false); showToast('Added “' + s.name + '” to ' + pipe.label); };
  /* Persist edits and apply them to the live funnel (cards, column header, breakdown). */
  const applyStages = () => {
    try { localStorage.setItem('e8-stage-pipelines-v1', JSON.stringify(pipes)); } catch (e) {}
    window.E8DATA.stagePipelines = pipes;
    if (window.e8BuildPipelineStages) window.E8DATA.pipelineStages = window.e8BuildPipelineStages(pipes);
    window.dispatchEvent(new Event('e8-stages-changed'));
    showToast('Pipeline saved - job cards updated');
  };

  return (
    <React.Fragment>
      <Topbar
        crumbs={[{ label: 'Stages' }]}
        actions={
          <React.Fragment>
            <DScfg.Button variant="ghost" size="sm" icon="tune" onClick={() => navigate('workfloweditor')}>Open in Workflow editor</DScfg.Button>
            <DScfg.Button variant="secondary" size="sm" icon="add" onClick={() => setAddOpen(true)}>New stage</DScfg.Button>
            <DScfg.Button variant="primary" size="sm" icon="check" onClick={applyStages}>Save changes</DScfg.Button>
          </React.Fragment>
        }
      />
      <div className="e8-content">
        <div className="e8-page">
          <div className="e8-pagehead">
            <div>
              <h1 className="e8-h1">Stages</h1>
              <div className="e8-pagehead-sub">Configure the pipelines records move through - SLAs, conversion and the automations that fire on each stage</div>
            </div>
          </div>

          {/* Pipeline tabs */}
          <div style={{ margin: '4px 0 14px' }}>
            <DScfg.SubTabs
              items={pipes.map((p) => ({ id: p.id, label: p.label, count: p.stages.length }))}
              active={pid}
              onChange={setPid}
            />
          </div>

          {/* Stat band */}
          <div className="e8-cfg-stats">
            {[['Stages', String(stages.length)], ['Avg SLA', avgSla + 'd'], ['Automations', String(totalAutos)], ['In flight', String(inFlight)]].map(([k, v]) => (
              <div key={k} className="e8-cfg-stat"><div className="e8-cfg-stat-k">{k}</div><div className="e8-cfg-stat-v tnum">{v}</div></div>
            ))}
          </div>

          {/* Flow viz */}
          <div className="e8-card" style={{ boxShadow: 'none', padding: '16px', marginBottom: 16, overflowX: 'auto' }}>
            <div className="e8-sectionlabel" style={{ marginBottom: 12 }}>Flow · conversion between stages</div>
            <StageFlow stages={stages} />
          </div>

          {/* Stage config cards */}
          <div className="e8-sectionlabel" style={{ marginBottom: 8 }}>Stage configuration</div>
          <div style={{ display: 'grid', gap: 8 }}>
            {stages.map((s, i) => (
              <div key={s.key} className="e8-stage-card">
                <span className="e8-stage-dot" style={{ background: STAGE_CAT[s.category].color }}></span>
                <div className="e8-stage-main">
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 'var(--ui-text-base)', fontWeight: 600 }}>{s.name}</span>
                    <DScfg.Badge tone={STAGE_CAT[s.category].tone}>{STAGE_CAT[s.category].label}</DScfg.Badge>
                    <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>{s.count} in stage{s.conversion != null ? ' · ' + s.conversion + '% advance' : ''}</span>
                  </div>
                  {s.description ? <div style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)', marginTop: 2 }}>{s.description}</div> : null}
                  {s.automations.length ? (
                    <div className="e8-stage-autos">
                      {s.automations.map((a) => (
                        <button key={a} type="button" className="e8-stage-auto" title="AI / automation on enter - click to remove" onClick={() => removeAuto(s.key, a)}>
                          <span className="material-symbols-outlined" style={{ fontSize: 12 }}>bolt</span>{a}
                          <span className="material-symbols-outlined e8-stage-auto-x" style={{ fontSize: 13 }}>close</span>
                        </button>
                      ))}
                    </div>
                  ) : null}
                </div>
                {s.category === 'open' ? (
                  <div className="e8-stage-sla">
                    <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>SLA</span>
                    <div className="e8-cfg-stepper sm">
                      <button type="button" onClick={() => setSla(s.key, s.slaDays - 1)}><span className="material-symbols-outlined" style={{ fontSize: 15 }}>remove</span></button>
                      <span className="tnum">{s.slaDays}d</span>
                      <button type="button" onClick={() => setSla(s.key, s.slaDays + 1)}><span className="material-symbols-outlined" style={{ fontSize: 15 }}>add</span></button>
                    </div>
                  </div>
                ) : <div className="e8-stage-sla" style={{ visibility: 'hidden' }}></div>}
                <div className="e8-stage-reorder">
                  <button type="button" title="Move up" disabled={i === 0} onClick={() => move(i, -1)}><span className="material-symbols-outlined" style={{ fontSize: 16 }}>keyboard_arrow_up</span></button>
                  <button type="button" title="Move down" disabled={i === stages.length - 1} onClick={() => move(i, 1)}><span className="material-symbols-outlined" style={{ fontSize: 16 }}>keyboard_arrow_down</span></button>
                </div>
                <DScfg.MenuButton
                  items={[
                    { icon: 'bolt', label: 'Add automation', onClick: () => showToast('Automation builder opens here') },
                    { icon: 'palette', label: 'Change color', onClick: () => showToast('Color picker opens here') },
                    { separator: true },
                    { icon: 'delete', label: 'Delete stage', danger: true, onClick: () => confirmRemoveStage(s) },
                  ]}
                />
              </div>
            ))}
          </div>
          <div className="e8-listfoot">{stages.length} stages · {totalAutos} automations · changes apply to new {pipe.object.toLowerCase()} records immediately</div>
        </div>
      </div>
      {addOpen ? <AddStageDialog onAdd={addStage} onClose={() => setAddOpen(false)} /> : null}
      {dialog}
    </React.Fragment>
  );
}

/* ============================== WORKFLOWS ============================== */
function WorkflowsScreen() {
  const D = window.E8DATA;
  const C = window.E8Charts;
  const { showToast } = React.useContext(window.E8Ctx);

  const deriveStatus = (wf) => wf.saved === 'Draft' ? 'draft' : (wf.active ? 'active' : 'paused');

  const [wfs, setWfs] = React.useState(() => {
    try { const s = JSON.parse(localStorage.getItem('e8-workflows-v1')); if (s && s.length) return s; } catch (e) {}
    return D.workflows.map((w) => ({ ...w, status: deriveStatus(w) }));
  });
  React.useEffect(() => { try { localStorage.setItem('e8-workflows-v1', JSON.stringify(wfs)); } catch (e) {} }, [wfs]);
  const [tab, setTab] = React.useState('all');

  const meta = (id) => D.workflowMeta[id] || { category: 'General', successRate: 0, runsSpark: [0, 0, 0, 0, 0, 0], owner: '-' };

  const counts = {
    all: wfs.length,
    active: wfs.filter((w) => w.status === 'active').length,
    paused: wfs.filter((w) => w.status === 'paused').length,
    drafts: wfs.filter((w) => w.status === 'draft').length,
  };

  const filtered = tab === 'all' ? wfs
    : tab === 'active' ? wfs.filter((w) => w.status === 'active')
    : tab === 'paused' ? wfs.filter((w) => w.status === 'paused')
    : wfs.filter((w) => w.status === 'draft');

  /* KPI derived values */
  const activeWfs = wfs.filter((w) => w.status === 'active');
  const runsThisWeek = wfs.reduce((n, w) => {
    const m = meta(w.id);
    return n + (m.runsSpark[m.runsSpark.length - 1] || 0);
  }, 0);
  const avgSuccess = activeWfs.length
    ? Math.round((activeWfs.reduce((n, w) => n + meta(w.id).successRate, 0) / activeWfs.length) * 100)
    : 0;

  const toggleActive = (id) => {
    const wf = wfs.find((w) => w.id === id);
    const nextStatus = wf.status === 'active' ? 'paused' : 'active';
    setWfs(wfs.map((w) => w.id === id ? { ...w, status: nextStatus } : w));
    showToast('"' + wf.name + '" ' + (nextStatus === 'active' ? 'activated' : 'paused'));
  };

  const { confirm, dialog } = window.useConfirm();
  const deleteWf = (id) => {
    const wf = wfs.find((w) => w.id === id);
    confirm({
      title: 'Delete “' + wf.name + '”?',
      body: 'This automation will stop running for everyone. You can undo right after, but it can’t be recovered later.',
      confirmLabel: 'Delete workflow',
      onConfirm: () => { const prev = wfs; setWfs(wfs.filter((w) => w.id !== id)); showToast('"' + wf.name + '" deleted', 'Undo', () => setWfs(prev)); },
    });
  };

  return (
    <React.Fragment>
      <Topbar
        crumbs={[{ label: 'Workflows' }]}
        actions={
          <React.Fragment>
            <DScfg.Button variant="secondary" size="sm" icon="library_books" onClick={() => showToast('Template gallery opens here')}>Templates</DScfg.Button>
            <DScfg.Button variant="primary" size="sm" icon="add" onClick={() => navigate('workfloweditor')}>New workflow</DScfg.Button>
          </React.Fragment>
        }
      />
      <div className="e8-content">
        <div className="e8-page">
          <div className="e8-pagehead">
            <div>
              <h1 className="e8-h1">Workflows</h1>
              <div className="e8-pagehead-sub">Automations that run the desk - triggers, agents, approvals and the humans in the loop</div>
            </div>
          </div>

          {/* KPI band */}
          <div className="e8-kpi-row">
            <KpiCard label="Active" value={String(counts.active)} delta={counts.active + ' of ' + wfs.length + ' running'} dir="up" spark={[2, 2, 2, 2, 2, counts.active]} />
            <KpiCard label="Runs this week" value={String(runsThisWeek)} delta="+12% vs last week" dir="up" spark={[8, 10, 11, 13, 14, runsThisWeek]} />
            <KpiCard label="Success rate" value={avgSuccess + '%'} delta="across active workflows" dir={avgSuccess >= 90 ? 'up' : 'flat'} spark={[88, 90, 91, 91, 93, avgSuccess]} />
            <KpiCard label="Time saved" value="36 hrs/wk" delta="+4 hrs vs last week" dir="up" spark={[22, 26, 28, 31, 34, 36]} />
          </div>

          {/* Filter tabs */}
          <div style={{ margin: '4px 0 16px' }}>
            <DScfg.SubTabs
              items={[
                { id: 'all', label: 'All', count: counts.all },
                { id: 'active', label: 'Active', count: counts.active },
                { id: 'paused', label: 'Paused', count: counts.paused },
                { id: 'drafts', label: 'Drafts', count: counts.drafts },
              ]}
              active={tab}
              onChange={setTab}
            />
          </div>

          {/* Workflow cards grid */}
          <div className="e8-wf-mgr-grid">
            {filtered.map((wf) => {
              const m = meta(wf.id);
              const trigger = wf.nodes[0] ? wf.nodes[0].title : '-';
              const steps = wf.nodes.length;
              const successPct = Math.round(m.successRate * 100);

              return (
                <div key={wf.id} className="e8-wf-mgr-card">
                  {/* Card head: name + status control */}
                  <div className="e8-wf-mgr-head">
                    <button
                      type="button"
                      className="e8-wf-mgr-name"
                      onClick={() => navigate('workfloweditor')}
                    >
                      {wf.name}
                    </button>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
                      <DScfg.Badge tone={m.category === 'Sourcing' ? 'accent' : m.category === 'Client comms' ? 'info' : 'neutral'}>
                        {m.category}
                      </DScfg.Badge>
                      {wf.status === 'draft'
                        ? <DScfg.Badge tone="neutral">Draft</DScfg.Badge>
                        : <DScfg.Toggle checked={wf.status === 'active'} onChange={() => toggleActive(wf.id)} />
                      }
                    </div>
                  </div>

                  {/* Description */}
                  <div className="e8-wf-mgr-desc">{wf.desc}</div>

                  {/* Trigger + steps meta */}
                  <div className="e8-wf-mgr-meta">
                    <span className="material-symbols-outlined" style={{ fontSize: 13, color: 'var(--ui-text-tertiary)' }}>play_arrow</span>
                    <span>{trigger}</span>
                    <span style={{ color: 'var(--ui-text-tertiary)' }}>·</span>
                    <span>{steps} step{steps !== 1 ? 's' : ''}</span>
                  </div>

                  {/* Runs sparkline + success rate */}
                  <div className="e8-wf-mgr-stats">
                    <div className="e8-wf-mgr-stat">
                      <span style={{ flex: '0 0 72px' }}>
                        {C ? <C.Sparkline data={m.runsSpark} tone="up" w={72} h={24} /> : null}
                      </span>
                      <span className="tnum" style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)' }}>{wf.runs} runs</span>
                    </div>
                    <div className="e8-wf-mgr-stat">
                      <span style={{ width: 56, display: 'inline-flex' }}>
                        <DScfg.Progress value={successPct} soft={successPct < 75} />
                      </span>
                      <span className="tnum" style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)' }}>{successPct}%</span>
                    </div>
                  </div>

                  {/* Owner + last run */}
                  <div className="e8-wf-mgr-owner">
                    <DScfg.Avatar name={m.owner} size="sm" />
                    <span style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)' }}>{m.owner}</span>
                    <span style={{ marginLeft: 'auto', fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>{wf.lastRun}</span>
                  </div>

                  {/* Footer */}
                  <div className="e8-wf-mgr-footer">
                    <DScfg.Button variant="secondary" size="sm" icon="edit" onClick={() => navigate('workfloweditor')}>Open in editor</DScfg.Button>
                    <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>{wf.saved}</span>
                    <DScfg.MenuButton
                      items={[
                        { icon: 'content_copy', label: 'Duplicate', onClick: () => showToast('"' + wf.name + '" duplicated') },
                        wf.status === 'active'
                          ? { icon: 'pause', label: 'Pause workflow', onClick: () => toggleActive(wf.id) }
                          : { icon: 'play_arrow', label: 'Activate workflow', onClick: () => toggleActive(wf.id) },
                        { separator: true },
                        { icon: 'delete', label: 'Delete workflow', danger: true, onClick: () => deleteWf(wf.id) },
                      ]}
                    />
                  </div>
                </div>
              );
            })}
          </div>

          {/* Template gallery */}
          <div style={{ marginTop: 32 }}>
            <div className="e8-sectionlabel" style={{ marginBottom: 12 }}>Start from a template</div>
            <div className="e8-wf-tpl-grid">
              {D.workflowTemplates.map((tpl) => (
                <div key={tpl.id} className="e8-wf-tpl-card">
                  <div className="e8-wf-tpl-icon">
                    <span className="material-symbols-outlined" style={{ fontSize: 22 }}>{tpl.icon}</span>
                  </div>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 'var(--ui-text-base)', fontWeight: 600, marginBottom: 3 }}>{tpl.name}</div>
                    <div style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)', lineHeight: 1.4 }}>{tpl.desc}</div>
                  </div>
                  <DScfg.Button variant="secondary" size="sm" onClick={() => navigate('workfloweditor')}>Use</DScfg.Button>
                </div>
              ))}
            </div>
          </div>

          <div className="e8-listfoot">{wfs.length} workflows · {counts.active} active · {counts.paused} paused · {counts.drafts} draft{counts.drafts === 1 ? '' : 's'}</div>
        </div>
      </div>
      {dialog}
    </React.Fragment>
  );
}

/* ============================== FORMS ============================== */
function FormsScreen() {
  const D = window.E8DATA;
  const { showToast } = React.useContext(window.E8Ctx);
  const forms = D.forms;
  const templates = D.formTemplates;

  /* Object filter tabs */
  const objects = ['All', ...Array.from(new Set(forms.map((f) => f.object)))];
  const [objTab, setObjTab] = React.useState('all');
  const [selectedId, setSelectedId] = React.useState(forms[0] ? forms[0].id : null);

  /* Empty-data guard: nothing to list or select. */
  if (!forms.length) {
    return (
      <React.Fragment>
        <Topbar crumbs={[{ label: 'Forms' }]} />
        <div className="e8-content"><div className="e8-page">
          <div style={{ maxWidth: 460, margin: '48px auto' }}>
            <DScfg.EmptyState icon="list_alt" title="No forms yet" body="Forms capture data across the funnel - public applications, client feedback and internal scorecards. Create one to get started." />
          </div>
        </div></div>
      </React.Fragment>
    );
  }

  const filtered = objTab === 'all' ? forms : forms.filter((f) => f.object === objTab);

  /* Always resolve selected form; guard against filter removing the selection */
  const sel = forms.find((f) => f.id === selectedId) || forms[0];

  /* Stat band derived values */
  const totalSubs = forms.reduce((n, f) => n + f.submissions, 0);
  const published = forms.filter((f) => f.status === 'published');
  const avgCompletion = published.length
    ? Math.round((published.reduce((n, f) => n + f.completion, 0) / published.length) * 100)
    : 0;

  /* Tab items with counts */
  const tabItems = objects.map((o) => ({
    id: o === 'All' ? 'all' : o,
    label: o,
    count: o === 'All' ? forms.length : forms.filter((f) => f.object === o).length,
  }));

  return (
    <React.Fragment>
      <Topbar
        crumbs={[{ label: 'Forms' }]}
        actions={
          <React.Fragment>
            <DScfg.Button variant="secondary" size="sm" icon="library_books" onClick={() => showToast('Template gallery opens here')}>Templates</DScfg.Button>
            <DScfg.Button variant="primary" size="sm" icon="add" onClick={() => showToast('Form builder opens here')}>New form</DScfg.Button>
          </React.Fragment>
        }
      />
      <div className="e8-content">
        <div className="e8-page">
          {/* Page head */}
          <div className="e8-pagehead">
            <div>
              <h1 className="e8-h1">Forms</h1>
              <div className="e8-pagehead-sub">The forms that capture data across the funnel - public, client and internal</div>
            </div>
          </div>

          {/* Stat band */}
          <div className="e8-cfg-stats">
            {[
              ['Forms', String(forms.length)],
              ['Submissions', totalSubs.toLocaleString()],
              ['Avg completion', avgCompletion + '%'],
              ['Published', String(published.length)],
            ].map(([k, v]) => (
              <div key={k} className="e8-cfg-stat">
                <div className="e8-cfg-stat-k">{k}</div>
                <div className="e8-cfg-stat-v tnum">{v}</div>
              </div>
            ))}
          </div>

          {/* Object filter tabs */}
          <div style={{ margin: '4px 0 14px' }}>
            <DScfg.SubTabs items={tabItems} active={objTab} onChange={setObjTab} />
          </div>

          {/* Two-pane layout */}
          <div className="e8-form-layout">
            {/* LEFT: form list */}
            <div className="e8-form-list">
              {filtered.map((form) => (
                <button
                  key={form.id}
                  type="button"
                  className={'e8-form-row' + (form.id === sel.id ? ' is-active' : '')}
                  onClick={() => setSelectedId(form.id)}
                >
                  <div className="e8-form-row-main">
                    <span style={{ fontWeight: 500, fontSize: 'var(--ui-text-base)', color: 'var(--ui-text)', display: 'block' }}>{form.name}</span>
                    <span style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)', display: 'block', marginTop: 2 }}>{form.object} · {form.channel}</span>
                  </div>
                  <div className="e8-form-row-meta">
                    <DScfg.Badge tone={form.status === 'published' ? 'success' : 'neutral'}>
                      {form.status === 'published' ? 'Published' : 'Draft'}
                    </DScfg.Badge>
                    <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', marginTop: 4, display: 'block' }}>
                      {form.submissions.toLocaleString()} submissions · {Math.round(form.completion * 100)}% complete
                    </span>
                  </div>
                </button>
              ))}
            </div>

            {/* RIGHT: preview panel */}
            <div className="e8-form-preview e8-card">
              {/* Header */}
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10, marginBottom: 10 }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 6 }}>
                    <span style={{ fontSize: 'var(--ui-text-lg)', fontWeight: 600 }}>{sel.name}</span>
                    <DScfg.Badge tone={sel.status === 'published' ? 'success' : 'neutral'}>
                      {sel.status === 'published' ? 'Published' : 'Draft'}
                    </DScfg.Badge>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                    <span className="e8-techchip">{sel.channel}</span>
                    <span className="e8-techchip">Used on {sel.usedOn}</span>
                    <span className="e8-techchip">{sel.preview.length} fields</span>
                  </div>
                </div>
              </div>

              {/* Description */}
              <p style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)', margin: '0 0 14px', lineHeight: 1.45 }}>{sel.desc}</p>

              {/* Fields section */}
              <div className="e8-sectionlabel" style={{ marginBottom: 8 }}>Fields</div>
              <div className="e8-form-fields-list">
                {sel.preview.map((field, i) => {
                  const meta = FIELD_TYPE_META[field.type] || FIELD_TYPE_META.text;
                  return (
                    <div key={i} className="e8-form-field-row">
                      <span className="material-symbols-outlined" style={{ fontSize: 16, color: 'var(--ui-text-tertiary)', flex: 'none' }}>{meta.icon}</span>
                      <span style={{ flex: 1, minWidth: 0, fontSize: 'var(--ui-text-base)', color: 'var(--ui-text)' }}>{field.label}</span>
                      <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', whiteSpace: 'nowrap' }}>{meta.label}</span>
                      {field.required ? <DScfg.Badge tone="accent">Required</DScfg.Badge> : null}
                    </div>
                  );
                })}
              </div>

              {/* Stats strip */}
              <div className="e8-form-stats-strip">
                <div>
                  <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', display: 'block' }}>Submissions</span>
                  <span style={{ fontSize: 'var(--ui-text-md)', fontWeight: 600 }} className="tnum">{sel.submissions.toLocaleString()}</span>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
                    <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>Completion</span>
                    <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-secondary)' }} className="tnum">{Math.round(sel.completion * 100)}%</span>
                  </div>
                  <DScfg.Progress value={Math.round(sel.completion * 100)} soft={sel.completion < 0.6} />
                </div>
                <div>
                  <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', display: 'block' }}>Last edited</span>
                  <span style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)' }}>{sel.lastEdited}</span>
                </div>
              </div>

              {/* Footer actions */}
              <div className="e8-form-preview-foot">
                <DScfg.Button variant="primary" size="sm" icon="edit" onClick={() => showToast('Form builder opens here')}>Edit in builder</DScfg.Button>
                <DScfg.Button variant="secondary" size="sm" icon="visibility" onClick={() => showToast('Form preview opens here')}>Preview</DScfg.Button>
                <DScfg.Button variant="ghost" size="sm" icon="content_copy" onClick={() => showToast('"' + sel.name + '" duplicated')}>Duplicate</DScfg.Button>
              </div>
            </div>
          </div>

          {/* Template gallery */}
          <div style={{ marginTop: 32 }}>
            <div className="e8-sectionlabel" style={{ marginBottom: 12 }}>Start from a template</div>
            <div className="e8-wf-tpl-grid">
              {templates.map((tpl) => (
                <div key={tpl.id} className="e8-wf-tpl-card">
                  <div className="e8-wf-tpl-icon">
                    <span className="material-symbols-outlined" style={{ fontSize: 22 }}>{tpl.icon}</span>
                  </div>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 'var(--ui-text-base)', fontWeight: 600, marginBottom: 3 }}>{tpl.name}</div>
                    <div style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)', lineHeight: 1.4 }}>{tpl.desc}</div>
                  </div>
                  <DScfg.Button variant="secondary" size="sm" onClick={() => showToast('Form builder opens here')}>Use</DScfg.Button>
                </div>
              ))}
            </div>
          </div>

          <div className="e8-listfoot">{forms.length} forms · {published.length} published · {forms.length - published.length} draft{(forms.length - published.length) === 1 ? '' : 's'} · {totalSubs.toLocaleString()} total submissions</div>
        </div>
      </div>
    </React.Fragment>
  );
}

Object.assign(window, { FieldsScreen, StagesScreen, WorkflowsScreen, FormsScreen });
