// T2 Falcon Admin — Templates: helper components + tree + WhatsApp preview

const { useState: useStateT, useEffect: useEffectT, useMemo: useMemoT, useRef: useRefT } = React;

// Display dates as DD-Mon-YYYY (e.g. "12-Mar-2025") to match the Contracts module. Seed dates
// are stored as "DD/MM/YYYY"; anything that doesn't match is returned unchanged (safe no-op).
const TPL_MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const tplFmtDate = (s) => {
  const m = String(s == null ? '' : s).trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
  if (!m) return s == null ? '' : s;
  return `${m[1].padStart(2, '0')}-${TPL_MONTHS[+m[2] - 1] || m[2]}-${m[3]}`;
};
window.tplFmtDate = tplFmtDate;

// ---- Brand logo helper (uses existing data brand colors) ----
const TplBrandLogo = ({ brand, size = 22 }) => {
  const map = {
    aramco: { bg: 'linear-gradient(135deg, #00B5A7, #00827A)', label: 'A' },
    alrajhi: { bg: '#0D5C5C', label: 'R' },
    snb: { bg: 'linear-gradient(135deg, #5B2E91, #4A2580)', label: 'S' },
    bupa: { bg: '#E8F1F8', label: 'B', color: '#0860A8' },
    generic: { bg: '#9CA3AF', label: '?' },
  };
  const m = map[brand] || map.generic;
  return (
    <span className="row-logo client" style={{ width: size, height: size, background: m.bg, color: m.color || 'white', fontSize: 10, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
      {m.label}
    </span>
  );
};

// Folder/node logo (uses initials)
const TplNodeLogo = ({ name }) => {
  const initials = (name || '').split(/\s+/).map(w => w[0]).filter(Boolean).slice(0, 2).join('').toUpperCase() || 'N';
  return (
    <span className="row-logo" style={{ background: '#D9E6DD', color: '#0d3f44', fontSize: 9, fontWeight: 700 }}>
      {initials}
    </span>
  );
};

// ---- Org tree (left rail) ----
// Wraps the real ClientsTree (from hierarchy.jsx) in the same .clients-panel
// chrome used on the Hierarchy page so the look is identical across pages.
const TplOrgTree = ({ tree, selected, selectNode, expanded, toggleExpand, t, hideRoot = false, hideSectionLabel = false, hideMenus = false, hideChevrons = false, rootClickable = true }) => {
  const [ctxOpenFor, setCtxOpenFor] = useStateT(null);
  return (
    <div className="clients-panel">
      <ClientsTree
        tree={tree}
        expanded={expanded}
        toggleExpand={toggleExpand}
        selected={selected}
        selectNode={selectNode}
        ctxOpenFor={ctxOpenFor}
        setCtxOpenFor={setCtxOpenFor}
        onCtxAction={() => setCtxOpenFor(null)}
        t={t}
        hideRoot={hideRoot}
        hideSectionLabel={hideSectionLabel}
        hideMenus={hideMenus}
        hideChevrons={hideChevrons}
        rootClickable={rootClickable}
      />
    </div>
  );
};

// Render WhatsApp-style inline formatting (*bold* _italic_ ~strike~ `mono`)
// and newlines as React nodes. Keeps everything safe — no innerHTML.
const renderWaText = (text) => {
  if (!text) return null;
  // Split into lines, then for each line walk the markdown-ish marks.
  // Marks must hug non-space chars on both sides, à la WhatsApp.
  const segRe = /(\*[^*\n]+\*|_[^_\n]+_|~[^~\n]+~|`[^`\n]+`)/g;
  const lines = String(text).split('\n');
  return lines.map((line, li) => {
    const parts = line.split(segRe);
    const nodes = parts.map((seg, i) => {
      if (!seg) return null;
      if (seg.length >= 2) {
        const first = seg[0], last = seg[seg.length - 1];
        if (first === last && '*_~`'.includes(first)) {
          const inner = seg.slice(1, -1);
          if (first === '*') return <strong key={i}>{inner}</strong>;
          if (first === '_') return <em key={i}>{inner}</em>;
          if (first === '~') return <s key={i}>{inner}</s>;
          if (first === '`') return <code key={i} style={{ fontFamily: 'monospace', background: 'rgba(0,0,0,0.05)', padding: '0 3px', borderRadius: 3 }}>{inner}</code>;
        }
      }
      return <React.Fragment key={i}>{seg}</React.Fragment>;
    });
    return <React.Fragment key={li}>{nodes}{li < lines.length - 1 ? <br /> : null}</React.Fragment>;
  });
};

// ---- WhatsApp preview (right rail / details) ----
const TplWAPreview = ({ tpl, t, showSheet = false, allOptionsOpen = false, onCloseAllOptions }) => {
  if (!tpl) return null;

  const kind = tpl.previewKind || 'live';

  // Header media for fixed-preview kinds (used in details view for sample tpls)
  const mediaMap = {
    feedback: 'linear-gradient(135deg, #fbbf24, #f59e0b)',
    shop:     'linear-gradient(135deg, #ec4899, #be185d)',
    track:    'linear-gradient(135deg, #06b6d4, #0e7490)',
  };
  const showMediaFixed = ['feedback', 'shop', 'track'].includes(kind);

  // Build action rows. If the wizard provided live buttons/flow, use them; otherwise fall back
  // to the per-kind canned actions used by the static example templates.
  const liveButtons = tpl.buttons || [];
  const liveFlow = tpl.flow;

  // Action icons — small inline SVGs that match the Template Preview reference.
  const IcView   = <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18"/></svg>;
  const IcReply  = <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg>;
  const IcList   = <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="4" cy="6" r="1"/><circle cx="4" cy="12" r="1"/><circle cx="4" cy="18" r="1"/></svg>;
  const IcCart   = <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.7 13.4a2 2 0 0 0 2 1.6h9.7a2 2 0 0 0 2-1.6L23 6H6"/></svg>;
  const IcCopy   = <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>;
  const IcOpen   = <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>;
  const IcPhone  = <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z"/></svg>;
  const IcBolt   = <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>;

  // Per-kind canned actions. The "feedback" template (Welcome Message) matches
  // the reference exactly: View FLow · Quick Replay · See All Options.
  const fixedActions = {
    feedback: [
      { icon: IcView,  label: t.previewViewFlow },
      { icon: IcReply, label: t.previewQuickReplay },
      { icon: IcList,  label: t.previewSeeAll },
    ],
    otp:    [{ icon: IcCopy, label: t.previewCopyCode }],
    signup: [{ icon: IcOpen, label: t.previewSignUp }],
    shop:   [
      { icon: IcCart, label: t.previewShopNow },
      { icon: IcView, label: t.previewViewFlow },
    ],
    track:  [{ icon: IcOpen, label: t.previewTrackShipment }],
  }[kind];

  const iconForKind = (k) => ({
    custom: IcReply,
    visit:  IcOpen,
    wa:     IcPhone,
    phone:  IcPhone,
  })[k] || IcReply;

  let actions = [];
  if (fixedActions) {
    actions = fixedActions.map(a => ({ ...a, kind: 'cta' }));
  } else {
    actions = liveButtons.map(b => ({
      kind: b.kind,
      icon: iconForKind(b.kind),
      label: b.text || (b.kind === 'visit' ? 'Visit website' : b.kind === 'wa' ? 'Call on WhatsApp' : b.kind === 'phone' ? 'Call us' : 'Reply'),
    }));
    if (liveFlow && liveFlow.type) {
      actions.push({ kind: 'flow', icon: IcBolt, label: liveFlow.buttonText || t.flowGetFeedback });
    }
  }

  // Show media bar in live mode if a media sample is selected (and it's not 'none')
  const liveMediaKind = tpl.mediaSampleId && tpl.mediaSampleId !== 'none' ? tpl.mediaSampleId : null;
  const showMediaLive = !fixedActions && !!liveMediaKind;
  const showMedia = showMediaFixed || showMediaLive;

  // Per-kind visual for the live media bar
  const liveMediaBg = {
    image:    'linear-gradient(135deg, #94a3b8, #475569)',
    video:    'linear-gradient(135deg, #1f2937, #111827)',
    document: 'linear-gradient(135deg, #fef3c7, #fbbf24)',
    location: 'linear-gradient(135deg, #bae6fd, #0284c7)',
  };
  const liveMediaIcon = {
    image: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.95 }}>
        <rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="M21 15l-5-5L5 21"/>
      </svg>
    ),
    video: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="white" stroke="white" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.95 }}>
        <polygon points="8 5 19 12 8 19 8 5"/>
      </svg>
    ),
    document: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#7c2d12" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="15" y2="17"/>
      </svg>
    ),
    location: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="white" stroke="#0c4a6e" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3" fill="#0c4a6e" stroke="#0c4a6e"/>
      </svg>
    ),
  };

  return (
    <div className="tpl-wa-frame">
      <div className="tpl-wa-bubble-group">
      <div className={`tpl-wa-bubble ${showMedia ? 'with-media' : ''} ${actions.length > 0 ? 'has-actions' : ''}`}>
        {showMedia && (
          <div
            className="media"
            style={{
              background: showMediaFixed
                ? mediaMap[kind]
                : (liveMediaBg[liveMediaKind] || 'linear-gradient(135deg, #94a3b8, #475569)'),
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            {liveMediaKind && liveMediaIcon[liveMediaKind]}
            {liveMediaKind === 'location' && tpl.location && (tpl.location.address || tpl.location.lat) && (
              <div style={{
                position: 'absolute', left: 8, right: 8, bottom: 6,
                background: 'rgba(255,255,255,0.92)', color: '#0c4a6e',
                fontSize: 10, fontWeight: 600, padding: '4px 6px', borderRadius: 4,
                textAlign: 'center', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
              }}>
                {tpl.location.address || `${tpl.location.lat}, ${tpl.location.lng || ''}`}
              </div>
            )}
          </div>
        )}
        <div className="body">
          {(tpl.title || tpl.header) && <div style={{ fontWeight: 700, marginBottom: 4 }}>{renderWaText(tpl.title || tpl.header)}</div>}
          <div>{renderWaText(tpl.body || tpl.bodyText)}</div>
          {tpl.footer && <div style={{ marginTop: 6, fontSize: 11, color: 'rgba(0,0,0,0.55)' }}>{renderWaText(tpl.footer)}</div>}
          <div className="ts">02:42 pm</div>
        </div>
      </div>
      {actions.length > 0 && (() => {
        // Up to 3 buttons → show all. More than 3 → show the first 2 and
        // collapse the rest behind a "See all options" pill (matches Meta's
        // own preview behaviour).
        const visible = actions.length <= 3 ? actions : actions.slice(0, 2);
        const collapsed = actions.length > 3;
        const IcListView = (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="4" cy="6" r="1"/><circle cx="4" cy="12" r="1"/><circle cx="4" cy="18" r="1"/></svg>
        );
        return (
          <div className="tpl-wa-actions">
            {visible.map((a, i) => (
              <div key={i} className="tpl-wa-action">
                <span className="tpl-wa-action-ic">{a.icon}</span>
                <span>{a.label}</span>
              </div>
            ))}
            {collapsed && (
              <div className="tpl-wa-action">
                <span className="tpl-wa-action-ic">{IcListView}</span>
                <span>{t.previewSeeAllOptions || 'See all options'}</span>
              </div>
            )}
          </div>
        );
      })()}
      </div>

      {/* Bottom sheet — opened by the play icon in the preview header.
          Lists every added action; Custom (Quick Reply) buttons are separated
          from Call-to-Action buttons by a horizontal divider. */}
      {allOptionsOpen && actions.length > 0 && (() => {
        const customs = actions.filter(a => a.kind === 'custom');
        const ctas = actions.filter(a => a.kind !== 'custom');
        return (
          <>
            <div className="tpl-wa-allopts-scrim" />
            <div className="tpl-wa-allopts-sheet">
              <div className="grip"></div>
              <div className="head">
                <span className="x" role="button" tabIndex={0} onClick={() => onCloseAllOptions && onCloseAllOptions()}><IcClose size={14} stroke={2} /></span>
                <span className="title">{t.allOptionsTitle || 'All Options'}</span>
                <span className="spacer"></span>
              </div>
              <div className="list">
                {customs.map((a, i) => (
                  <div key={'q-'+i} className="row">
                    <span className="row-ic">{a.icon}</span>
                    <span className="row-lbl">{a.label}</span>
                  </div>
                ))}
                {customs.length > 0 && ctas.length > 0 && <div className="divider" />}
                {ctas.map((a, i) => (
                  <div key={'c-'+i} className="row">
                    <span className="row-ic">{a.icon}</span>
                    <span className="row-lbl">{a.label}</span>
                  </div>
                ))}
              </div>
            </div>
          </>
        );
      })()}

      {showSheet && kind === 'signup' && (
        <div className="tpl-wa-sheet">
          <div className="grip"></div>
          <div className="head">
            <span>Sign up</span>
            <span className="x"><IcClose size={12} /></span>
          </div>
          <div className="field">First name</div>
          <div className="field">Last name</div>
          <div className="field">Email</div>
          <div className="submit">Submit</div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { TplBrandLogo, TplNodeLogo, TplOrgTree, TplWAPreview });
