// T2 Falcon Admin — Templates: Top-level page orchestrator

const { useState: useStateP, useMemo: useMemoP, useEffect: useEffectP } = React;

// ---- Falcon / Client perspective picker (first screen) ----
const TplViewAsPicker = ({ t, onPick }) => {
  return (
    <div className="tpl-picker-page">
      <div className="tpl-picker-card">
        <div className="tpl-picker-head">
          <div>
            <h2>{t.tplPickerTitle}</h2>
            <p>{t.tplPickerSubtitle}</p>
          </div>
        </div>
        <div className="tpl-picker-grid">
          <button
            className="tpl-picker-tile falcon"
            onClick={() => onPick('falcon')}
          >
            <span className="ic-wrap"><T2Mark size={28} color="white" /></span>
            <span className="ttl">{t.tplShowAsFalcon}</span>
            <span className="dsc">{t.tplShowAsFalconDesc}</span>
            <span className="cta">{t.tplShowAsFalcon} <IcChevronRight size={14} stroke={2} /></span>
          </button>
          <button
            className="tpl-picker-tile client"
            onClick={() => onPick('client')}
          >
            <span className="ic-wrap"><IcBuildingS size={26} stroke={1.7} /></span>
            <span className="ttl">{t.tplShowAsClient}</span>
            <span className="dsc">{t.tplShowAsClientDesc}</span>
            <span className="cta">{t.tplShowAsClient} <IcChevronRight size={14} stroke={2} /></span>
          </button>
        </div>
      </div>
    </div>
  );
};

const TemplatesPage = ({ tree, selected, selectNode, expanded, toggleExpand, lang, t, pushToast }) => {
  // viewAs: null (picker) | 'falcon' | 'client'
  const [viewAs, setViewAs] = useStateP(null);
  // Mode: 'list' | 'create' | 'details'
  const [mode, setMode] = useStateP('list');
  const [tab, setTab] = useStateP('templates'); // templates | pending | shared
  const [search, setSearch] = useStateP('');
  const [channel, setChannel] = useStateP('all');
  const [openMenuId, setOpenMenuId] = useStateP(null);
  const [activeTpl, setActiveTpl] = useStateP(null);

  // List controls lifted from TemplatesList so they sit in the node-header (alongside client name)
  const [createOpen, setCreateOpen] = useStateP(false);
  const [filterOpen, setFilterOpen] = useStateP(false);
  // Whether the preview's "All Options" sheet is open (toggled by the play
  // icon in the preview header).
  const [allOptionsOpen, setAllOptionsOpen] = useStateP(false);
  // Resizable preview rail (IVR review): null = default width; otherwise a px override.
  const [previewW, setPreviewW] = useStateP(null);
  const startPreviewResize = (e) => {
    if (e.button !== 0) return;
    e.preventDefault();
    const panel = e.currentTarget.closest('.tpl-preview');
    if (!panel) return;
    const startX = e.clientX;
    const startW = panel.getBoundingClientRect().width;
    const onMove = (ev) => { const w = Math.max(264, Math.min(680, startW + (startX - ev.clientX))); setPreviewW(w); };
    const onUp = () => { document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onUp); document.body.style.userSelect = ''; document.body.style.cursor = ''; };
    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseup', onUp);
    document.body.style.userSelect = 'none';
    document.body.style.cursor = 'col-resize';
  };
  const createRef = React.useRef(null);
  const filterRef = React.useRef(null);
  useEffectP(() => {
    const onDoc = (e) => {
      if (filterRef.current && !filterRef.current.contains(e.target)) setFilterOpen(false);
      if (createRef.current && !createRef.current.contains(e.target)) setCreateOpen(false);
      // Close the row action menu when clicking anywhere outside an actions cell.
      if (!(e.target.closest && e.target.closest('.tpl-actions-cell'))) setOpenMenuId(null);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  // Wizard state lifted here so we can render its header actions in the page
  const [wizStep, setWizStep] = useStateP(1);
  const [wizData, setWizData] = useStateP({
    category: 'Marketing', subCategory: 'Default', language: 'English', sharedIds: [], referenceId: '',
    variableType: 'Number',
  });

  // Flow modal stack
  const [flowTypeOpen, setFlowTypeOpen] = useStateP(false);
  const [flowTypeInitialTab, setFlowTypeInitialTab] = useStateP('create');
  const [flowEditorOpen, setFlowEditorOpen] = useStateP(false);
  const [savedFlow, setSavedFlow] = useStateP(null);
  const [editingFlow, setEditingFlow] = useStateP(null);
  // Edit screen doubles as the Share screen (read-only + only "Shared With" enabled).
  const [isShareMode, setIsShareMode] = useStateP(false);

  // ---- View-scoped tree ----
  // Falcon view: full tree.
  // Client view: re-root at Aramco, dropping the Falcon root above.
  const findInTree = (node, id) => {
    if (!node) return null;
    if (node.id === id) return node;
    for (const c of (node.children || [])) {
      const r = findInTree(c, id);
      if (r) return r;
    }
    return null;
  };

  const scopedTree = useMemoP(() => {
    if (viewAs === 'client') {
      const aramco = findInTree(tree, 'aramco');
      return aramco || tree;
    }
    return tree;
  }, [tree, viewAs]);

  // When entering client view, force the tree selection to aramco/its first child
  // so the right-hand panel makes sense.
  useEffectP(() => {
    if (viewAs === 'client') {
      const stillValid = findInTree(scopedTree, selected);
      if (!stillValid) selectNode('aramco');
    }
  }, [viewAs]); // eslint-disable-line

  // Data per tab
  const data = useMemoP(() => {
    if (tab === 'templates') return window.seedTemplates;
    if (tab === 'pending')   return window.pendingTemplates;
    return window.sharedTemplates;
  }, [tab]);

  const scopeNode = findInTree(scopedTree, selected) || scopedTree;

  const onView = (tpl) => {
    setActiveTpl(tpl);
    setIsShareMode(false);
    setMode('details');
    setOpenMenuId(null);
  };

  const onCreateOpen = (createChannel) => {
    if (viewAs !== 'client') return; // create only allowed in client view
    setMode('create');
    setSavedFlow(null);
    setWizStep(1);
    const ch = createChannel || 'WhatsApp';
    if (ch === 'IVR Voice') {
      setWizData({
        channel: 'IVR Voice',
        language: 'English',
        sharedIds: [], referenceId: '',
        ivr: window.defaultIvrData ? window.defaultIvrData('static') : { type: 'static', nodes: [{ id: 'n_root', parent: null, key: null, label: 'Welcome', segments: [], terminal: null }], variables: [] },
      });
    } else {
      setWizData({ channel: 'WhatsApp', category: 'Marketing', subCategory: 'Default', language: 'English', sharedIds: [], referenceId: '', wabaAccount: '', variableType: 'Number' });
    }
  };

  // Map a template into the edit/share form's data shape (resolving Shared-With names → ids).
  const tplToWizData = (tpl) => {
    const cands = window.sharedWithCandidates || [];
    const sharedIds = tpl.sharedIds || (tpl.sharedWith || []).map(nm => (cands.find(c => c.name === nm) || {}).id).filter(Boolean);
    return {
      _editId: tpl.id,
      channel: tpl.channel || 'WhatsApp',
      name: tpl.name || '',
      language: tpl.language || 'English',
      referenceId: tpl.referenceId || '',
      wabaAccount: tpl.wabaAccount || '',
      category: tpl.serviceType || 'Marketing',
      subCategory: tpl.subCategory || 'Default',
      variableType: tpl.variableType || 'Number',
      header: tpl.header || '',
      body: tpl.body || '',
      footer: tpl.footer || '',
      buttons: (tpl.buttons || []).map(b => ({ ...b })),
      flow: tpl.flow ? { ...tpl.flow } : null,
      samples: { ...(tpl.samples || {}) },
      sharedIds,
      mediaSampleId: tpl.mediaSampleId || '',
      status: tpl.status || '',
      // System/read-only detail fields, shown (locked) so the Edit/Share screen mirrors the
      // Template Details card.
      createdBy: tpl.createdBy || '',
      creationDate: tpl.creationDate || '',
      creationTime: tpl.creationTime || '',
      // Maker–checker review data — carried through so the Edit/Share screens can show
      // the same "Action history" table as the More-Details view.
      checker1: tpl.checker1 || null,
      checker2: tpl.checker2 || null,
      // IVR voice flow — deep-cloned so canvas edits don't mutate the seed until Save.
      // `_seededType` marks the flow as already-seeded for its type, so the Step-2 canvas's
      // "seed once per type" effect PRESERVES these existing nodes instead of wiping them.
      ivr: tpl.ivr ? { ...JSON.parse(JSON.stringify(tpl.ivr)), _seededType: tpl.ivr.type } : undefined,
    };
  };

  // Open the single-page Edit screen, pre-filled from the (internally-rejected) template.
  const onEditOpen = (tpl) => {
    if (!tpl) return;
    setIsShareMode(false);
    setMode('edit'); setWizStep(1); setSavedFlow(null);
    setWizData(tplToWizData(tpl));
  };

  // Open in read-only "Share" mode (only Shared-With is editable).
  // IVR Voice templates reuse the two-column "More Details" layout (Template Details +
  // Action history + IVR Voice Flow rail); WhatsApp keeps the single-page edit form.
  const onShareOpen = (tpl) => {
    if (!tpl) return;
    setIsShareMode(true);
    setSavedFlow(null);
    setWizData(tplToWizData(tpl));
    const tplIsIvr = tpl.channel === 'IVR Voice' || tpl.channel === 'Voice';
    if (tplIsIvr) {
      setActiveTpl(tpl);
      setMode('details');
    } else {
      setMode('edit'); setWizStep(1);
    }
  };

  // Save sharing only — update who the template is shared with (status unchanged).
  const onShareSave = () => {
    const cands = window.sharedWithCandidates || [];
    const tpl = (window.seedTemplates || []).find(x => x.id === wizData._editId);
    if (tpl) {
      const ids = wizData.sharedIds || [];
      tpl.sharedWith = ids.map(id => (cands.find(c => c.id === id) || {}).name).filter(Boolean);
      tpl.sharedWithCount = 0;
    }
    setMode('list');
    pushToast(t.toastTplShared || 'Sharing updated');
  };

  // Resubmit an edited template → it re-enters the workflow as Pending.
  const onEditSave = () => {
    const list = window.seedTemplates || [];
    const tpl = list.find(x => x.id === wizData._editId);
    if (tpl) {
      tpl.name = wizData.name; tpl.language = wizData.language; tpl.referenceId = wizData.referenceId;
      if (tpl.channel === 'IVR Voice') {
        // Voice: save the edited canvas tree; Template ID & Service Type stay locked.
        tpl.ivr = wizData.ivr;
      } else {
        tpl.serviceType = wizData.category; tpl.subCategory = wizData.subCategory;
        tpl.header = wizData.header; tpl.body = wizData.body; tpl.footer = wizData.footer;
        tpl.buttons = wizData.buttons; tpl.flow = wizData.flow; tpl.samples = wizData.samples;
        tpl.variableType = wizData.variableType;
      }
      // Back into the review workflow, no longer rejected.
      tpl.status = 'pending';
      tpl.metaRejected = false;
      tpl.statusByMeta = '---';
      tpl.checker1 = { name: '---', status: 'pending' };
      tpl.checker2 = { name: '---', status: 'pending' };
    }
    setMode('list');
    pushToast(t.toastTplResubmitted || 'Template resubmitted — status: Pending');
  };

  // Apply saved flow when it returns from the flow editor
  useEffectP(() => {
    if (savedFlow) setWizData(d => ({ ...d, flow: { ...d.flow, ...savedFlow } }));
  }, [savedFlow]);

  const isIvr = wizData.channel === 'IVR Voice';
  const wizCanNext = isIvr
    ? (wizStep === 1
        ? !!(wizData.name && wizData.ivr && wizData.ivr.type)
        : wizStep === 2
          // Step 2 (canvas builder) valid once at least one node exists, and every
          // variable (if any) has a sample. Lets you reach Share & Submit (step 3).
          ? (() => {
              const ivr = wizData.ivr || {};
              const hasNode = (ivr.nodes || []).length > 0;
              const varsOk = (ivr.variables || []).every(v => (v.sample || '').toString().trim().length > 0);
              return hasNode && varsOk;
            })()
          : true)
    : (wizStep === 1
        ? wizData.name && wizData.language && wizData.category && wizData.subCategory
        : wizStep === 2
          // Authentication templates don't have a Body field — Step 2 has its own
          // Code delivery / Content / Validity layout, so allow Next once the user reaches it.
          ? (wizData.category === 'Authentication' ? true : !!wizData.body)
          : true);

  const channels = ['all', 'WhatsApp', 'Voice', 'SMS', 'Email'];
  const channelLabel = (c) => c === 'all' ? t.allChannels : (c === 'WhatsApp' ? t.chWhatsApp : c === 'Voice' ? t.chVoice : c === 'SMS' ? t.chSMS : t.chEmail);

  const ScopeAvatar = () => {
    if (!scopeNode) return null;
    if (scopeNode.id === 'falcon' || scopeNode.type === 'root') {
      return <span className="node-avatar"><IcFalcon size={18} /></span>;
    }
    if (scopeNode.type === 'client') return <BrandLogo brand={scopeNode.brand} size={32} />;
    return (
      <span className="node-avatar" style={{ background: '#0d3f44', color: 'white' }}>
        <span style={{ fontSize: 12, fontWeight: 700 }}>{(scopeNode.name || 'N').slice(0, 1)}</span>
      </span>
    );
  };

  // ---------- PICKER PAGE ----------
  if (viewAs === null) {
    return <TplViewAsPicker t={t} onPick={(v) => { setViewAs(v); setMode('list'); }} />;
  }

  const isFalcon = viewAs === 'falcon';
  const isClient = viewAs === 'client';

  // Right-rail preview shown for create mode AND for details (with WhatsApp template content).
  // The IVR create wizard hides the phone preview on ALL steps (1 Basic Info,
  // 2 the canvas builder, 3 Share & Submit) so the wizard always gets full width.
  // IVR details/share/pending also hide the rail — the flow canvas is shown full-width
  // INLINE inside the details page (TplDetailsPage), matching the IVR Edit screen.
  const detailsIsIvr = mode === 'details' && activeTpl && (activeTpl.channel === 'IVR Voice' || activeTpl.channel === 'Voice');
  const ivrHidePreview = (isIvr && (mode === 'create' || mode === 'edit')) || detailsIsIvr;
  const showPreview = (mode === 'create' || mode === 'edit' || mode === 'details') && !ivrHidePreview;
  const previewTpl = mode === 'details' ? activeTpl
                    : ((mode === 'create' || mode === 'edit') ? (isIvr ? {
                        channel: 'IVR Voice',
                        previewKind: 'ivr',
                        ivr: wizData.ivr,
                        name: wizData.name || '',
                      } : (() => {
                        // Substitute filled-in variable samples into preview text
                        // so the Meta preview reflects the same content the user
                        // will submit. Empty samples keep the {{token}} visible.
                        const substitute = (text) => {
                          if (!text) return text;
                          const samples = wizData.samples || {};
                          return String(text).replace(/\{\{[^{}]*\}\}/g, (m) => (samples[m] && samples[m].length ? samples[m] : m));
                        };
                        // Authentication templates have an auto-generated body
                        // driven by the checkboxes on step 2, plus a fixed
                        // "Copy code" CTA (previewKind: 'otp').
                        if (wizData.category === 'Authentication') {
                          const a = wizData.auth || {};
                          const addSecurity = a.addSecurity !== false; // default ON
                          const addExpiration = a.addExpiration === true; // default OFF
                          const expiresInRaw = (a.expiresInRaw !== undefined) ? a.expiresInRaw : '10';
                          const expN = parseInt(expiresInRaw, 10);
                          const lines = [t.authBodyBase || '{{1}} is your verification code.'];
                          if (addSecurity) lines.push(t.authBodySecurity || 'For your security, do not share this code.');
                          if (addExpiration && !isNaN(expN) && expN >= 1 && expN <= 90) {
                            const tpl = t.authBodyExpires || 'This code expires in {n} minutes.';
                            lines.push(tpl.replace('{n}', expN));
                          }
                          return {
                            previewKind: 'otp',
                            body: lines.join('\n'),
                            footer: '',
                            buttons: [],
                          };
                        }
                        return {
                          title: substitute(wizData.header) || '',
                          header: substitute(wizData.header) || '',
                          body: substitute(wizData.body) || (lang === 'ar' ? 'سيظهر معاينة محتوى القالب هنا أثناء الكتابة.' : 'Hello — your template body preview will appear here as you type.'),
                          footer: substitute(wizData.footer) || '',
                          buttons: wizData.buttons || [],
                          flow: wizData.flow || null,
                          mediaSampleId: wizData.mediaSampleId || '',
                          location: wizData.location || null,
                        };
                      })()) : null);
  const previewIsIvr = previewTpl && (previewTpl.channel === 'IVR Voice' || previewTpl.channel === 'Voice' || previewTpl.previewKind === 'ivr');

  return (
    <div className={`templates-page ${showPreview ? 'with-preview' : ''}`} style={previewW ? { '--tpl-preview-w': previewW + 'px' } : undefined}>
      <TplOrgTree
        tree={scopedTree}
        selected={selected}
        selectNode={selectNode}
        expanded={expanded}
        toggleExpand={toggleExpand}
        t={t}
        hideRoot={false}
        hideSectionLabel={mode === 'create'}
        hideMenus={true}
        hideChevrons={true}
        rootClickable={false}
      />

      <div className="content-panel tpl-main">
        {/* Page-level tabs — matches Hierarchy's .tabs-bar inside .content-panel */}
        {mode === 'list' && isClient && (
          <div className="tabs-bar tpl-page-tabs">
            <div className="tabs-bar-left">
              <button className={`tab ${tab === 'templates' ? 'active' : ''}`} onClick={() => setTab('templates')}>{t.tabTemplates}</button>
              <button className={`tab ${tab === 'pending' ? 'active' : ''}`} onClick={() => setTab('pending')}>{t.tabPendingReview}</button>
              <button className={`tab ${tab === 'shared' ? 'active' : ''}`} onClick={() => setTab('shared')}>{t.tabSharedTemplates}</button>
            </div>
          </div>
        )}
        {mode === 'list' && isFalcon && (
          <div className="tabs-bar tpl-page-tabs">
            <div className="tabs-bar-left">
              <button className="tab active" type="button" disabled>{t.tabTemplates}</button>
            </div>
          </div>
        )}

        {/* Create mode uses the ac-page shell (matches Create New Client) */}
        {mode === 'create' && (
          <div className="ac-page tpl-ac-page">
            <div className="ac-topbar">
              <div className="ac-topbar-brand">
                <span className="ac-brand-mark">
                  {scopeNode?.type === 'client'
                    ? <BrandLogo brand={scopeNode.brand} size={26} />
                    : <T2Mark size={26} color="#0d3f44" />}
                </span>
                <span className="ac-brand-name">{scopeNode?.name || 'Falcon'}</span>
              </div>
              <div className="ac-topbar-actions">
                <button className="btn btn-secondary" type="button" onClick={() => setMode('list')}>{t.cancel}</button>
                {wizStep > 1 && (
                  <button
                    className="btn btn-secondary"
                    type="button"
                    onClick={() => setWizStep(s => Math.max(1, s - 1))}
                  >{t.previous}</button>
                )}
                {wizStep < 3 ? (
                  <button
                    className="btn btn-primary"
                    type="button"
                    disabled={!wizCanNext}
                    onClick={() => setWizStep(s => s + 1)}
                  >{t.next}</button>
                ) : (
                  <button
                    className="btn btn-primary"
                    type="button"
                    onClick={() => {
                      setMode('list');
                      pushToast(t.toastTplCreated);
                    }}
                  >{t.submit}</button>
                )}
              </div>
            </div>
            <div className="ac-body">
              {isIvr ? (
                <TplIvrWizard
                  t={t}
                  lang={lang}
                  step={wizStep}
                  data={wizData}
                  setData={setWizData}
                />
              ) : (
                <TplWizard
                  t={t}
                  lang={lang}
                  step={wizStep}
                  data={wizData}
                  setData={setWizData}
                  openFlowType={(tab) => { setFlowTypeInitialTab(tab === 'existing' ? 'existing' : 'create'); setFlowTypeOpen(true); }}
                  openFlowEditor={(flow) => { setEditingFlow(flow); setFlowEditorOpen(true); }}
                />
              )}
            </div>
          </div>
        )}

        {/* Edit mode — single-page "Edit Template" form (internally-rejected templates only) */}
        {mode === 'edit' && (
          <div className="ac-page tpl-ac-page">
            <div className="ac-topbar">
              <div className="ac-topbar-brand">
                <span className="ac-brand-mark">
                  {scopeNode?.type === 'client'
                    ? <BrandLogo brand={scopeNode.brand} size={26} />
                    : <T2Mark size={26} color="#0d3f44" />}
                </span>
                <span className="ac-brand-name">{scopeNode?.name || 'Falcon'}</span>
              </div>
              <div className="ac-topbar-actions">
                <button className="btn btn-secondary" type="button" onClick={() => setMode('list')}>{t.cancel}</button>
                <button className="btn btn-primary" type="button" onClick={isShareMode ? onShareSave : onEditSave}>{t.save || 'Save'}</button>
              </div>
            </div>
            <div className="ac-body">
              {isIvr ? (
                <TplIvrEditForm
                  t={t}
                  lang={lang}
                  data={wizData}
                  setData={setWizData}
                  readOnly={isShareMode}
                />
              ) : (
                <TplEditForm
                  t={t}
                  lang={lang}
                  data={wizData}
                  setData={setWizData}
                  readOnly={isShareMode}
                  openFlowType={(tab) => { setFlowTypeInitialTab(tab === 'existing' ? 'existing' : 'create'); setFlowTypeOpen(true); }}
                  openFlowEditor={(flow) => { setEditingFlow(flow); setFlowEditorOpen(true); }}
                />
              )}
            </div>
          </div>
        )}

        {(mode !== 'create' && mode !== 'edit') && (
        <div className="content-body tpl-main-body">
        {/* Scope header — matches Organization Hierarchy .node-header.
            Hidden in details mode: TplDetailsPage renders its own User-Profile-
            style top bar (no Falcon text/icon, Back button on right). */}
        {mode !== 'details' && (
        <div className={`node-header tpl-node-header ${isFalcon ? 'falcon-view' : 'client-view'}`}>
          <div className={`node-title ${scopeNode && (scopeNode.id === 'falcon' || scopeNode.type === 'root') ? 'falcon' : ''}`}>
            <ScopeAvatar />
            <span>{scopeNode ? scopeNode.name : t.templatesPageTitle}</span>
            <span className={`tpl-view-badge ${isFalcon ? 'falcon' : 'client'}`}>
              {isFalcon ? t.tplFalconBadge : t.tplClientBadge}
            </span>
            <button
              className="tpl-back-to-picker"
              onClick={() => { setViewAs(null); setMode('list'); selectNode('falcon'); }}
              title={t.tplBackToPicker}
            >
              <IcArrowLeft size={12} stroke={1.7} /> {t.tplBackToPicker}
            </button>
          </div>
          {mode === 'list' && isClient && tab === 'templates' && (
            <div className="node-actions tpl-node-actions">
              <div className="btn-create-tpl" ref={createRef}>
                <button className="btn btn-primary tpl-create-btn" onClick={() => setCreateOpen(o => !o)}>
                  <IcPlus size={14} stroke={2.2} />
                  {t.createTemplate}
                </button>
                {createOpen && (
                  <div className="ch-menu">
                    <div className="ch-item first" onClick={() => { setCreateOpen(false); onCreateOpen('WhatsApp'); }}>
                      <span className="icw"><IcWa size={14} stroke={1.8} /></span>
                      {t.chWhatsApp}
                    </div>
                    <div className="ch-item" onClick={() => { setCreateOpen(false); onCreateOpen('IVR Voice'); }}>
                      <span className="icw"><IcPhone size={14} stroke={1.8} /></span>
                      {lang === 'ar' ? 'الصوت IVR' : 'IVR Voice'}
                    </div>
                    <div className="ch-item" onClick={() => { setCreateOpen(false); pushToast('SMS template flow coming soon'); }}>
                      <span className="icw"><IcSms size={14} stroke={1.8} /></span>
                      {t.chSMS}
                    </div>
                    <div className="ch-item" onClick={() => { setCreateOpen(false); pushToast('Email template flow coming soon'); }}>
                      <span className="icw"><IcMail size={14} stroke={1.8} /></span>
                      {t.chEmail}
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
        )}

        {mode === 'list' && (
          <TemplatesList
            tab={tab}
            setTab={setTab}
            templates={data}
            search={search}
            setSearch={setSearch}
            channel={channel}
            setChannel={setChannel}
            t={t}
            lang={lang}
            onView={onView}
            onEdit={onEditOpen}
            onShare={onShareOpen}
            onCreateOpen={onCreateOpen}
            openMenuId={openMenuId}
            setOpenMenuId={setOpenMenuId}
            pushToast={pushToast}
            readOnly={isFalcon}
            isClient={isClient}
          />
        )}

        {mode === 'details' && (
          <TplDetailsPage
            tpl={activeTpl}
            scopeNode={scopeNode}
            onBack={() => { setIsShareMode(false); setMode('list'); }}
            onApprove={() => setMode('list')}
            onReject={() => setMode('list')}
            t={t}
            lang={lang}
            pushToast={pushToast}
            readOnly={isFalcon}
            shareMode={isShareMode}
            sharedIds={wizData.sharedIds || []}
            onSharedChange={(ids) => setWizData({ ...wizData, sharedIds: ids })}
            onShareSave={onShareSave}
            onShareCancel={() => { setIsShareMode(false); setMode('list'); }}
            reviewMode={tab === 'pending'}
          />
        )}
        </div>
        )}
      </div>

      {showPreview && (
        <div className={`tpl-preview ${previewIsIvr ? 'is-ivr' : ''}`}>
          <div
            className="tpl-preview-resizer"
            role="separator"
            aria-orientation="vertical"
            aria-label={t.ivrResizeHint || 'Drag to resize · double-click to reset'}
            title={t.ivrResizeHint || 'Drag to resize · double-click to reset'}
            onMouseDown={startPreviewResize}
            onDoubleClick={() => setPreviewW(null)}
          >
            <span className="tpl-preview-grip" />
          </div>
          <div className="tpl-preview-head">
            <span>{previewIsIvr ? (t.ivrReviewHead || 'IVR Voice Flow') : (t.previewTitle || 'Template Preview')}</span>
            {!previewIsIvr && (
              <span
                className={`toggle ${allOptionsOpen ? 'is-open' : ''}`}
                onClick={() => setAllOptionsOpen(o => !o)}
                role="button"
                tabIndex={0}
                title={t.previewSeeAllOptions || 'See all options'}
                style={{ cursor: 'pointer' }}
              >
                {allOptionsOpen ? (
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 11V5a2 2 0 0 0-4 0v9"/><path d="M14 9a2 2 0 1 1 4 0v6"/><path d="M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-2a8 8 0 0 1-8-8 2 2 0 1 1 4 0"/></svg>
                ) : (
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><polygon points="6 4 20 12 6 20 6 4" /></svg>
                )}
              </span>
            )}
          </div>
          {previewIsIvr
            ? <div className="tpl-preview-ivr-canvas"><TplIvrStep2 key={previewTpl && previewTpl.id} data={previewTpl} setData={() => {}} t={t} readOnly={true} /></div>
            : <div className="tpl-preview-scroll">
                <TplWAPreview
                  tpl={previewTpl}
                  t={t}
                  showSheet={previewTpl?.previewKind === 'signup'}
                  allOptionsOpen={allOptionsOpen}
                  onCloseAllOptions={() => setAllOptionsOpen(false)}
                />
              </div>}
        </div>
      )}

      {flowTypeOpen && (
        <TplFlowTypeModal
          t={t}
          category={wizData.category}
          initialTab={flowTypeInitialTab}
          onClose={() => setFlowTypeOpen(false)}
          onCreate={(opt) => {
            setFlowTypeOpen(false);
            // Utility → "Get feedback" flow; everything else → the survey flow.
            const isFeedback = (opt && opt.id === 'feedback') || wizData.category === 'Utility';
            setEditingFlow(isFeedback ? window.defaultFeedbackFlow : window.defaultSurveyFlow);
            setFlowEditorOpen(true);
          }}
          onUseExisting={(flow) => {
            setFlowTypeOpen(false);
            setSavedFlow({ type: 'existing', source: 'existing', name: flow.name, id: Date.now().toString(36) });
            pushToast(t.toastFlowSaved);
          }}
        />
      )}

      {flowEditorOpen && (
        <TplFlowEditor
          flow={editingFlow || window.defaultSurveyFlow}
          t={t}
          onClose={() => { setFlowEditorOpen(false); setEditingFlow(null); }}
          onSave={(flow) => {
            setFlowEditorOpen(false);
            setEditingFlow(null);
            setSavedFlow(flow);
            pushToast(t.toastFlowSaved);
          }}
        />
      )}
    </div>
  );
};

window.TemplatesPage = TemplatesPage;
window.TplViewAsPicker = TplViewAsPicker;
