/* screens-templates.jsx - the Templates hub (one library for messaging, capture, documents)
   and the template editor (merge fields, AI assist, A/B performance). Self-wrapped screens
   reached via routes templates and templates/<id>. */
const DStpl = window.Stand8DesignSystem_b5c975;

function tplCount(key) {
  const t = window.E8DATA.templates || [];
  return key === 'all' ? t.length : t.filter((x) => x.type === key).length;
}

// Highlight merge-field tokens - both {{double}} and {single} brace styles.
function mergeFieldChips(text) {
  const segs = String(text || '').split(/(\{\{[^}]+\}\}|\{[a-zA-Z0-9_]+\})/g);
  return segs.map((s, i) => /^(\{\{[^}]+\}\}|\{[a-zA-Z0-9_]+\})$/.test(s)
    ? <span key={i} className="e8-mf">{s}</span>
    : <React.Fragment key={i}>{s}</React.Fragment>);
}

function TemplateCard({ t }) {
  const countLabel = t.mergeFields ? t.mergeFields.length + ' merge fields'
    : t.steps ? t.steps + ' steps'
    : t.fields ? t.fields + ' fields' : null;
  const lowVar = t.variants && t.variants.find((v) => !v.winner && v.reply != null && v.reply < 15);
  return (
    <div className="e8-tpl-card" {...window.clickableProps(() => navigate('templates/' + t.id))}>
      <span className={'e8-tpl-type t-' + t.type}>{t.type.toUpperCase()}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="e8-tpl-name">{t.name}</div>
        <div className="e8-tpl-prev">{t.preview}</div>
        <div className="e8-tpl-meta">
          <DStpl.ProvenanceBadge kind={t.provenance === 'drafted' ? 'drafted' : 'human'} />
          {countLabel ? <span>{countLabel}</span> : null}
          <span>Used {t.usage}x</span>
          {t.type === 'email' && t.perf ? <span className="e8-tpl-perf">{t.perf.open}% open · {t.perf.reply}% reply</span> : null}
          {t.linkedFeature ? <span style={{ color: 'var(--ui-accent, var(--ui-daybreak-text))' }}>{t.linkedFeature}</span> : null}
        </div>
        {lowVar ? (
          <div className="e8-tpl-nudge">
            <span>A variant is replying at {lowVar.reply}% - below average.</span>
            <DStpl.Button variant="ghost" size="sm" onClick={(ev) => { if (ev && ev.stopPropagation) ev.stopPropagation(); navigate('templates/' + t.id); }}>Improve with AI</DStpl.Button>
          </div>
        ) : null}
      </div>
    </div>
  );
}

// One workspace, type tabs across every template kind. "messaging" folds email + SMS together.
const TYPE_TABS = [
  { id: 'all', label: 'All', types: null },
  { id: 'messaging', label: 'Messaging', types: ['email', 'sms'] },
  { id: 'sequence', label: 'Sequences', types: ['sequence'] },
  { id: 'form', label: 'Forms', types: ['form'] },
  { id: 'scorecard', label: 'Scorecards', types: ['scorecard'] },
  { id: 'document', label: 'Documents', types: ['document'] },
  { id: 'casestudy', label: 'Case studies', types: ['casestudy'] },
];

function TemplatesHub() {
  const D = window.E8DATA;
  const { showToast } = React.useContext(E8Ctx);
  const [tab, setTab] = React.useState('all');
  const [q, setQ] = React.useState('');
  const ql = q.toLowerCase();
  const all = D.templates || [];
  const tabDef = TYPE_TABS.find((x) => x.id === tab) || TYPE_TABS[0];
  const inTab = (t) => !tabDef.types || tabDef.types.indexOf(t.type) >= 0;
  const list = all.filter((t) => inTab(t) && (!q || t.name.toLowerCase().includes(ql) || (t.preview || '').toLowerCase().includes(ql)));
  const countFor = (def) => def.types ? all.filter((t) => def.types.indexOf(t.type) >= 0).length : all.length;
  return (
    <React.Fragment>
      <Topbar
        crumbs={[{ label: 'Templates' }]}
        actions={
          <React.Fragment>
            <DStpl.Button variant="primary" size="sm" icon="auto_awesome" onClick={() => navigate('templates/new-email')}>Draft with AI</DStpl.Button>
            <DStpl.Button variant="secondary" size="sm" icon="add" onClick={() => navigate('templates/new-email')}>New template</DStpl.Button>
          </React.Fragment>
        }
      />
      <div className="e8-content">
        <div className="e8-page">
          <DStpl.SubTabs
            items={TYPE_TABS.map((d) => ({ id: d.id, label: d.label, count: countFor(d) }))}
            active={tab}
            onChange={setTab}
          />
          <div className="e8-tpl-toolbar">
            <DStpl.Input icon="search" placeholder="Search templates…" value={q} onChange={(e) => setQ(e.target ? e.target.value : e)} />
          </div>
          {list.length === 0
            ? <DStpl.EmptyState icon="search_off" title="No templates" body="Try a different search or type." />
            : <div className="e8-tpl-grid">{list.map((t) => <TemplateCard key={t.id} t={t} />)}</div>}
          <div className="e8-tpl-foot">Looking for field, stage or workflow templates? They live in <a className="e8-link" tabIndex={0} onKeyDown={window.keyActivate} onClick={() => navigate('fields')}>Fields</a>, <a className="e8-link" tabIndex={0} onKeyDown={window.keyActivate} onClick={() => navigate('stages')}>Stages</a> and <a className="e8-link" tabIndex={0} onKeyDown={window.keyActivate} onClick={() => navigate('workflows')}>Workflows</a> under Config.</div>
        </div>
      </div>
    </React.Fragment>
  );
}

const TEXT_TYPES = ['email', 'sms', 'document'];
const NEW_FIELDS = ['first_name', 'role', 'company', 'rate', 'day'];

// Local (no-AI) rewrite fallbacks so the assist buttons always do something visible.
function localRewrite(kind, text) {
  const s = String(text || '');
  if (kind === 'shorter') {
    const sentences = s.match(/[^.!?]+[.!?]+(\s|$)/g);
    if (!sentences || sentences.length < 2) return s;
    return sentences.slice(0, Math.ceil(sentences.length / 2)).join('').trim();
  }
  if (kind === 'warmer') {
    if (/hope you/i.test(s)) return s;
    return s.replace(/^(Hi [^,]+,?\s*)?/i, (m) => (m || '') + 'Hope you are doing well. ');
  }
  return s;
}

function TemplateEditor({ id }) {
  const D = window.E8DATA;
  const { showToast } = React.useContext(E8Ctx);
  const isNew = String(id || '').indexOf('new-') === 0;
  const newType = isNew ? id.slice(4) : null;
  const existing = (D.templates || []).find((x) => x.id === id);
  const t = existing || (isNew
    ? { id: id, type: newType || 'email', name: 'Untitled template', preview: '', body: '', mergeFields: NEW_FIELDS, provenance: 'drafted', usage: 0 }
    : null);
  const storeKey = 'e8-tpl-draft-' + id;
  const [body, setBody] = React.useState(function () {
    if (isNew) return '';
    try { const saved = window.localStorage.getItem(storeKey); if (saved != null) return saved; } catch (e) {}
    return t ? (t.body || t.preview || '') : '';
  });
  const [busy, setBusy] = React.useState(null);
  const taRef = React.useRef(null);
  React.useEffect(function () { if (isNew) return; try { window.localStorage.setItem(storeKey, body); } catch (e) {} }, [storeKey, body, isNew]);

  if (!t) {
    return (
      <React.Fragment>
        <Topbar crumbs={[{ label: 'Templates', to: 'templates' }, { label: 'Not found' }]} />
        <div className="e8-content"><div className="e8-page">
          <DStpl.EmptyState icon="search_off" title="Template not found" body="This template does not exist." />
        </div></div>
      </React.Fragment>
    );
  }

  const editable = TEXT_TYPES.indexOf(t.type) >= 0;
  const act = (l) => showToast ? showToast(l) : null;
  const fields = (t.mergeFields && t.mergeFields.length) ? t.mergeFields : NEW_FIELDS;

  const insertField = (f) => {
    const token = '{' + f + '}';
    const ta = taRef.current;
    if (ta && typeof ta.selectionStart === 'number') {
      const s0 = ta.selectionStart, e0 = ta.selectionEnd;
      setBody(body.slice(0, s0) + token + body.slice(e0));
      window.setTimeout(function () { try { ta.focus(); ta.selectionStart = ta.selectionEnd = s0 + token.length; } catch (e) {} }, 0);
    } else { setBody(body + token); }
  };

  const aiAssist = async (kind) => {
    setBusy(kind);
    const ai = window.E8AI;
    const prompts = {
      shorter: 'Rewrite this recruiting message to be shorter and punchier. Keep the meaning and any {tokens} intact:\n\n',
      warmer: 'Rewrite this recruiting message in a warmer, friendlier tone. Keep any {tokens} intact:\n\n',
    };
    try {
      const on = ai && ai.getState && ai.getState().enabled;
      if (on && ai.generate && prompts[kind]) {
        const out = await ai.generate(prompts[kind] + body, null);
        const tokens = body.match(/\{[a-zA-Z0-9_]+\}/g) || [];
        const keepsTokens = !!out && tokens.every((tk) => out.indexOf(tk) >= 0);
        if (out && out.trim() && keepsTokens) { setBody(out.trim()); act('Rewritten on-device'); }
        else { setBody(localRewrite(kind, body)); act('Applied (kept your merge fields)'); }
      } else { setBody(localRewrite(kind, body)); act('Applied (turn on on-device AI in Agents for smarter rewrites)'); }
    } catch (e) { setBody(localRewrite(kind, body)); act('Applied locally'); }
    setBusy(null);
  };

  const routeOut = () => {
    if (t.type === 'sequence') navigate('sequences/' + id + '/edit');
    else if (t.type === 'form' || t.type === 'scorecard') navigate('forms');
    else if (t.type === 'casestudy') navigate('casestudies');
  };
  const builderLabel = t.type === 'sequence' ? 'Open in sequence builder'
    : (t.type === 'form' || t.type === 'scorecard') ? 'Open in form builder'
    : t.type === 'casestudy' ? 'Open case study' : null;

  return (
    <React.Fragment>
      <Topbar
        crumbs={[{ label: 'Templates', to: 'templates' }, { label: isNew ? 'New template' : t.name }]}
        actions={
          <React.Fragment>
            {builderLabel ? <DStpl.Button variant="secondary" size="sm" icon="open_in_new" onClick={routeOut}>{builderLabel}</DStpl.Button> : null}
            {editable ? <DStpl.Button variant="ghost" size="sm" onClick={() => act('Preview (prototype)')}>Preview</DStpl.Button> : null}
            {editable ? <DStpl.Button variant="primary" size="sm" icon="save" onClick={() => act(isNew ? 'Template created (prototype)' : 'Template saved (prototype)')}>{isNew ? 'Create' : 'Save'}</DStpl.Button> : null}
          </React.Fragment>
        }
      />
      <div className="e8-content">
        <div className="e8-page">
          <div className="e8-te-wrap">
            <div className="e8-te-edit">
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span className={'e8-tpl-type t-' + t.type}>{t.type.toUpperCase()}</span>
                <DStpl.ProvenanceBadge kind={t.provenance === 'drafted' ? 'drafted' : 'human'} />
                {!isNew ? <span style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)' }}>Used {t.usage}x</span> : null}
              </div>

              {editable ? (
                <React.Fragment>
                  <div className="e8-te-l">Body</div>
                  <textarea ref={taRef} className="e8-te-ta" value={body} rows={8}
                    onChange={(e) => setBody(e.target.value)}
                    placeholder="Write your template. Insert merge fields like {first_name} below." />
                  <div className="e8-te-palette">
                    <div className="e8-te-l">Insert merge field</div>
                    {fields.map((f) => <button key={f} type="button" className="e8-te-chip" onClick={() => insertField(f)}>+ {f}</button>)}
                  </div>
                  <div className="e8-te-l">Preview</div>
                  <div className="e8-te-body">{body ? mergeFieldChips(body) : <span style={{ color: 'var(--ui-text-tertiary)' }}>Nothing yet - start typing above.</span>}</div>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <div className="e8-te-l">Preview</div>
                  <div className="e8-te-body">{mergeFieldChips(t.preview)}</div>
                  {builderLabel ? (
                    <div className="e8-te-builder">
                      <span>{t.type === 'sequence' ? 'Sequences are edited as a multi-step cadence.' : t.type === 'casestudy' ? 'Case studies open in the engagement record.' : 'Forms and scorecards are edited in the form builder.'}</span>
                      <DStpl.Button variant="secondary" size="sm" icon="open_in_new" onClick={routeOut}>{builderLabel}</DStpl.Button>
                    </div>
                  ) : null}
                </React.Fragment>
              )}
            </div>
            <div className="e8-te-rail">
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 9 }}>
                <span className="e8-sectionlabel">AI assist</span>
                <DStpl.ProvenanceBadge kind="advised" />
              </div>
              {editable ? (
                <React.Fragment>
                  <div className="e8-te-sug">Lead with a specific, concrete detail rather than a generic opener - messages that do tend to get ~11% more replies.</div>
                  <div className="e8-te-airow">
                    <DStpl.Button variant="secondary" size="sm" disabled={!!busy} onClick={() => aiAssist('shorter')}>{busy === 'shorter' ? 'Working…' : 'Make shorter'}</DStpl.Button>
                    <DStpl.Button variant="secondary" size="sm" disabled={!!busy} onClick={() => aiAssist('warmer')}>{busy === 'warmer' ? 'Working…' : 'Warmer tone'}</DStpl.Button>
                    <DStpl.Button variant="secondary" size="sm" onClick={() => act('New A/B variant created (prototype)')}>New A/B variant</DStpl.Button>
                  </div>
                </React.Fragment>
              ) : <div className="e8-te-sug">This template type is edited in its own builder. The AI rewrite tools apply to email, SMS and document templates.</div>}
              {t.variants ? (
                <React.Fragment>
                  <div className="e8-sectionlabel" style={{ margin: '16px 0 9px' }}>Performance · A/B</div>
                  {t.variants.map((v, i) => (
                    <div key={i} className={'e8-te-ab' + (v.winner ? ' win' : '')}>
                      <div className="e8-te-ab-h">Variant {v.label}{v.winner ? <span className="e8-te-win">WINNER</span> : null}</div>
                      <div className="e8-te-ab-bar"><span style={{ width: (v.reply || 0) + '%', background: v.winner ? 'var(--ui-success)' : 'var(--ui-text-tertiary)' }} /></div>
                      <div className="e8-te-ab-s">{v.reply}% reply · {v.open}% open · {v.sends} sends</div>
                    </div>
                  ))}
                  <div style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', marginTop: 8 }}>Auto-routes new sends to the winner once significance is reached.</div>
                </React.Fragment>
              ) : <div style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', marginTop: 8 }}>No A/B data yet.</div>}
            </div>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

Object.assign(window, { TemplatesHub, TemplateEditor });
