// T2 Falcon Admin — Meta Service (CommChannels & Services → Meta Service .Mng)
// Meta Unified Channel Manager. Flow: purchase → activate → channel hub. In the hub
// the client connects Meta assets (WhatsApp / Instagram / Facebook) via a simulated
// Meta "Embedded Signup" (Facebook Login for Business) popup → syncing → assets grid.

const { useState: useStateMeta, useRef: useRefMeta, useEffect: useEffectMeta } = React;

// ===== Brand glyphs =====
const MetaChannelIcon = ({ type, size = 22 }) => {
  if (type === 'whatsapp') return (
    <span className="meta-ch-ic wa" style={{ width: size, height: size }}>
      <svg width={size * 0.62} height={size * 0.62} viewBox="0 0 24 24" fill="#fff"><path d="M12 2a10 10 0 0 0-8.6 15l-1.2 4.4 4.5-1.2A10 10 0 1 0 12 2Zm5.3 14.1c-.2.6-1.3 1.2-1.8 1.2-.5.1-1 .1-3.3-.9-2.8-1.2-4.5-4-4.6-4.2-.1-.2-1.1-1.5-1.1-2.8s.7-2 .9-2.2c.2-.3.5-.3.7-.3h.5c.2 0 .4 0 .6.5l.8 1.9c.1.2.1.4 0 .5l-.4.5c-.2.2-.3.3-.1.6.2.3.8 1.3 1.7 2.1 1.2 1 2.1 1.4 2.4 1.5.2.1.4.1.5-.1l.7-.8c.2-.2.3-.2.5-.1l1.8.9c.2.1.4.2.4.3.1.2.1.9-.1 1.5Z"/></svg>
    </span>
  );
  if (type === 'instagram') return (
    <span className="meta-ch-ic ig" style={{ width: size, height: size }}>
      <svg width={size * 0.62} height={size * 0.62} viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="5" /><circle cx="12" cy="12" r="4" /><circle cx="17.5" cy="6.5" r="1.2" fill="#fff" stroke="none" /></svg>
    </span>
  );
  return (
    <span className="meta-ch-ic fb" style={{ width: size, height: size }}>
      <svg width={size * 0.62} height={size * 0.62} viewBox="0 0 24 24" fill="#fff"><path d="M14 9h2.5l.5-3H14V4.5c0-.9.3-1.5 1.6-1.5H17V.3C16.7.2 15.7 0 14.6 0 12.2 0 10.5 1.5 10.5 4.1V6H8v3h2.5v9H14V9Z"/></svg>
    </span>
  );
};
const metaTypeLabel = (type, t) =>
  type === 'whatsapp' ? (t.metaTypeWhatsapp || 'WhatsApp')
  : type === 'instagram' ? (t.metaTypeInstagram || 'Instagram')
  : (t.metaTypeFacebook || 'Facebook');

const MetaStatusPill = ({ status, t }) => {
  const map = {
    active:   { cls: 'active',   label: t.metaStatusActive || 'Active' },
    expired:  { cls: 'expired',  label: t.metaStatusExpired || 'Expired' },
    disabled: { cls: 'disabled', label: t.metaStatusDisabled || 'Disabled' },
  };
  const s = map[status] || map.active;
  return (
    <span className={`status-badge ${s.cls}`}>
      <span className="dot"></span>
      {s.label}
    </span>
  );
};

// ===== Simulated Meta OAuth popup (Embedded Signup) =====
const MetaOAuthPopup = ({ mode, t, onClose, onAllow }) => {
  const [scopes, setScopes] = useStateMeta({ wa: true, ig: true });
  const heading = mode === 'reauth' ? (t.metaReauthHeading || 'Re-authorize Your Business')
    : mode === 'manage' ? (t.metaManageHeading || 'Manage Your Permissions')
    : mode === 'remove' ? (t.metaRemoveHeading || 'Remove Your Connection')
    : (t.metaConnectHeading || 'Connect Your Business');
  return ReactDOM.createPortal(
    <div className="meta-oauth-overlay" onMouseDown={onClose}>
      <div className="meta-oauth" onMouseDown={(e) => e.stopPropagation()}>
        <div className="meta-oauth-bar">
          <span className="meta-oauth-url"><IcLock size={12} stroke={2} /> oauth.facebook.com</span>
          <button className="meta-oauth-x" onClick={onClose}><IcClose size={14} stroke={2} /></button>
        </div>
        <div className="meta-oauth-body">
          <div className="meta-oauth-logo"><span className="meta-logo-mark">∞</span> Meta</div>
          <div className="meta-oauth-h">{heading}</div>
          <div className="meta-oauth-sub">{t.metaOauthSub || 'Log in to use your Facebook account with Falcon.'}</div>
          <label className="meta-oauth-field"><span>{t.metaEmailPhone || 'Email or phone'}</span><input type="text" defaultValue="business@brand.com" /></label>
          <label className="meta-oauth-field"><span>{t.metaPassword || 'Password'}</span><input type="password" defaultValue="••••••••••" /></label>
          <button className="meta-oauth-login" type="button">{t.metaLogIn || 'Log In'}</button>
          <div className="meta-oauth-allow-h">{t.metaSelectAllow || 'Select what to allow:'}</div>
          <label className="meta-oauth-cb"><input type="checkbox" checked={scopes.wa} onChange={(e) => setScopes((s) => ({ ...s, wa: e.target.checked }))} /> <span>{t.metaScopeWa || 'Manage WhatsApp Business Accounts'}</span></label>
          <label className="meta-oauth-cb"><input type="checkbox" checked={scopes.ig} onChange={(e) => setScopes((s) => ({ ...s, ig: e.target.checked }))} /> <span>{t.metaScopeIg || 'Access Instagram Direct Messages'}</span></label>
          <button className="meta-oauth-allow" type="button" onClick={() => onAllow(scopes)}>{t.metaAllowContinue || 'Allow and Continue'}</button>
        </div>
      </div>
    </div>,
    document.body
  );
};

// ===== Syncing overlay =====
const MetaSyncingOverlay = ({ t }) => ReactDOM.createPortal(
  <div className="meta-sync-overlay">
    <div className="meta-sync-box">
      <span className="meta-spinner" />
      <span className="meta-sync-text">{t.metaSyncing || 'Syncing your Meta assets… Please wait.'}</span>
    </div>
  </div>,
  document.body
);

// ===== Purchase gate =====
const MetaPurchaseGate = ({ offer, t, onPurchase }) => (
  <div className="meta-gate">
    <div className="meta-gate-card">
      <div className="meta-gate-head">
        <span className="meta-gate-ic"><span className="meta-logo-mark lg">∞</span></span>
        <div>
          <div className="meta-gate-title">{offer.title}</div>
          <div className="meta-gate-sub">{offer.subtitle}</div>
        </div>
      </div>
      <div className="meta-gate-price">
        <span className="meta-price-val">{offer.price}</span>
        <span className="meta-price-per">{offer.pricePer}</span>
        <span className="meta-price-type">{offer.priceType}</span>
      </div>
      <div className="meta-gate-req">
        <div className="meta-gate-req-h">{t.metaActivationNeeds || "Before you purchase — what you'll need to activate:"}</div>
        <ul>
          {offer.requirements.map((r, i) => (
            <li key={i}><span className="meta-req-tick"><IcCheck size={11} stroke={3} /></span>{r}</li>
          ))}
        </ul>
      </div>
      <button className="btn btn-primary meta-gate-btn" onClick={onPurchase}>{t.metaPurchase || 'Purchase channel'}</button>
    </div>
  </div>
);

// ===== Activate gate =====
const MetaActivateGate = ({ offer, t, onActivate }) => (
  <div className="meta-gate">
    <div className="meta-gate-card">
      <div className="meta-gate-purchased"><span className="meta-purchased-tick"><IcCheck size={14} stroke={3} /></span> {t.metaPurchased || 'Channel purchased'}</div>
      <div className="meta-gate-head">
        <span className="meta-gate-ic"><span className="meta-logo-mark lg">∞</span></span>
        <div>
          <div className="meta-gate-title">{t.metaActivateTitle || 'Activate Meta Service'}</div>
          <div className="meta-gate-sub">{t.metaActivateSub || "Turn on the channel for your organization. You'll then connect your Meta accounts through Meta's secure login."}</div>
        </div>
      </div>
      <div className="meta-gate-req">
        <div className="meta-gate-req-h">{t.metaActivationNeeds2 || 'Activation connects your tenant to Meta:'}</div>
        <ul>
          {offer.requirements.map((r, i) => (
            <li key={i}><span className="meta-req-tick"><IcCheck size={11} stroke={3} /></span>{r}</li>
          ))}
        </ul>
      </div>
      <button className="btn btn-primary meta-gate-btn" onClick={onActivate}>{t.metaActivate || 'Activate channel'}</button>
    </div>
  </div>
);

// ===== Channel hub — empty state =====
const MetaHubEmpty = ({ t, onAdd }) => (
  <div className="meta-empty">
    <span className="meta-empty-ic"><IcGlobe size={30} stroke={1.5} /></span>
    <div className="meta-empty-title">{t.metaNoChannels || 'No channels connected yet.'}</div>
    <button className="btn btn-primary meta-empty-btn" onClick={onAdd}><IcPlus size={15} stroke={2} /> {t.metaAddAccount || 'Add New Meta Account'}</button>
    <div className="meta-empty-note">{t.metaAuthNote || 'By connecting, you will be securely redirected to Meta to authorize your business accounts.'}</div>
  </div>
);

// ===== Channel hub — row actions (3-dot menu, like the Templates list) =====
const MetaRowMenu = ({ open, row, t, onManage, onReauth, onRemove, onDisable, onEnable }) => {
  if (!open) return null;
  const { status } = row;
  return (
    <div className="row-menu" onClick={(e) => e.stopPropagation()}>
      {status === 'expired' && (
        <button className="row-menu-item" onClick={onReauth}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M23 4v6h-6M1 20v-6h6" /><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" /></svg>
          <span>{t.metaReauth || 'Re-auth'}</span>
        </button>
      )}
      {status === 'active' && (
        <button className="row-menu-item" onClick={onManage}>
          <IcSettings size={14} stroke={1.8} /> <span>{t.metaManage || 'Manage'}</span>
        </button>
      )}
      {status === 'active' && (
        <button className="row-menu-item" onClick={onDisable}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9" /><line x1="5.6" y1="5.6" x2="18.4" y2="18.4" /></svg>
          <span>{t.metaDisable || 'Disable'}</span>
        </button>
      )}
      {status === 'disabled' && (
        <button className="row-menu-item" onClick={onEnable}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9" /><polyline points="8 12.5 11 15.5 16 9.5" /></svg>
          <span>{t.metaEnable || 'Enable'}</span>
        </button>
      )}
      <button className="row-menu-item cg-danger-item" onClick={onRemove}>
        <IcTrash size={14} stroke={1.8} /> <span>{t.metaRemove || 'Remove'}</span>
      </button>
    </div>
  );
};

// ===== Channel hub — grid =====
const MetaChannelsGrid = ({ rows, t, onManage, onReauth, onRemove, onDisable, onEnable, openMenuId, setOpenMenuId }) => (
  <div className="table-panel tpl-table-panel meta-table-panel">
    <div className="table-head-bar tpl-head-bar"><div className="table-head-title">{t.metaTabAccounts || 'Accounts'}</div></div>
    <div className="table-scroll tpl-table-wrap">
      <table className="tpl-table meta-table">
        <thead>
          <tr>
            <th>{t.metaColType || 'Channel type'}</th>
            <th>{t.metaColAsset || 'Asset name / ID'}</th>
            <th>{t.metaColStatus || 'Status'}</th>
            <th className="col-actions">{t.metaColActions || 'Actions'}</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => {
            const isOpen = openMenuId === r.id;
            return (
              <tr key={r.id}>
                <td><span className="meta-type-cell"><MetaChannelIcon type={r.channelType} size={26} /> {metaTypeLabel(r.channelType, t)}</span></td>
                <td><span className="meta-asset"><strong>{r.asset}</strong>{r.assetSub && <span className="meta-asset-sub">{r.assetSub}</span>}</span></td>
                <td><MetaStatusPill status={r.status} t={t} /></td>
                <td className="col-actions" style={{ position: 'relative' }}>
                  <button className={`row-action-btn ${isOpen ? 'open' : ''}`} onClick={() => setOpenMenuId(isOpen ? null : r.id)} aria-label="Actions"><IcMore size={16} /></button>
                  <MetaRowMenu open={isOpen} row={r} t={t}
                    onManage={() => { setOpenMenuId(null); onManage(r); }}
                    onReauth={() => { setOpenMenuId(null); onReauth(r); }}
                    onRemove={() => { setOpenMenuId(null); onRemove(r); }}
                    onDisable={() => { setOpenMenuId(null); onDisable(r); }}
                    onEnable={() => { setOpenMenuId(null); onEnable(r); }} />
                </td>
              </tr>
            );
          })}
          {rows.length === 0 && <tr><td colSpan={4} className="meta-empty-row">{t.metaNoChannelsRow || 'No accounts connected yet — use “Add New Meta Account”.'}</td></tr>}
        </tbody>
      </table>
    </div>
  </div>
);

// ===== Page orchestrator =====
const MetaServicePage = ({ tree, selected, t = {}, pushToast }) => {
  const clients = (tree && tree.children) || [];
  const scopeNode = (() => {
    const n = (window.findNode && tree) ? window.findNode(tree, selected) : null;
    if (n && n.type === 'client') return n;
    return clients.find((c) => c.id === 'aramco') || clients[0] || n || { name: 'Meta Service', brand: 'aramco' };
  })();
  const offer = window.metaServiceOffer || { title: 'Meta Channels & Services', subtitle: '', price: '', pricePer: '', priceType: '', requirements: [] };

  // Lands directly on the "Accounts" tab hub (empty → Add → grid). The purchase/activate
  // gate components remain available (set initial phase to 'purchase' to re-enable them).
  const [phase, setPhase] = useStateMeta('hub'); // purchase | activate | hub
  // Landing shows the populated Accounts grid (the seeded Meta channels); the
  // "Add New Meta Account" button connects further assets on top.
  const [channels, setChannels] = useStateMeta(() => (window.seedMetaChannels || []).map((c) => ({ ...c })));
  const [firstAuthDone, setFirstAuthDone] = useStateMeta(true);
  const [popup, setPopup] = useStateMeta(null); // null | { mode:'add'|'manage'|'reauth', rowId? }
  const [syncing, setSyncing] = useStateMeta(false);
  const [openMenuId, setOpenMenuId] = useStateMeta(null); // open row action menu
  const timerRef = useRefMeta(null);
  useEffectMeta(() => () => clearTimeout(timerRef.current), []);
  // Close the row action menu on any outside click.
  useEffectMeta(() => {
    if (openMenuId == null) return;
    const onDown = (e) => { if (!e.target.closest('.row-menu') && !e.target.closest('.row-action-btn')) setOpenMenuId(null); };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [openMenuId]);

  const purchase = () => { setPhase('activate'); pushToast(t.metaPurchasedToast || 'Channel purchased ✓'); };
  const activate = () => { setPhase('hub'); pushToast(t.metaActivatedToast || 'Meta Service activated ✓'); };

  const openAdd = () => setPopup({ mode: 'add' });
  const openManage = (r) => setPopup({ mode: 'manage', rowId: r.id });
  const openReauth = (r) => setPopup({ mode: 'reauth', rowId: r.id });
  // Remove now goes through the same Meta popup as Manage (revoke access on Meta).
  const openRemove = (r) => setPopup({ mode: 'remove', rowId: r.id });
  const doDisable = (r) => { setChannels((list) => list.map((c) => (c.id === r.id ? { ...c, status: 'disabled' } : c))); pushToast(t.metaDisabledToast || 'Meta connection disabled'); };
  const doEnable = (r) => { setChannels((list) => list.map((c) => (c.id === r.id ? { ...c, status: 'active' } : c))); pushToast(t.metaEnabledToast || 'Meta connection enabled ✓'); };

  // Meta popup "Allow and Continue" → syncing → apply the result.
  const onAllow = () => {
    const p = popup;
    setPopup(null);
    setSyncing(true);
    timerRef.current = setTimeout(() => {
      setSyncing(false);
      if (!p) return;
      if (p.mode === 'add') {
        if (!firstAuthDone) {
          setChannels((window.seedMetaChannels || []).map((c) => ({ ...c })));
          setFirstAuthDone(true);
          pushToast(t.metaSyncedToast || 'Meta assets synced ✓');
        } else {
          const extras = window.metaExtraAssets || [];
          setChannels((list) => {
            const next = extras.find((e) => !list.some((c) => c.asset === e.asset));
            if (!next) { pushToast(t.metaNoMoreAssets || 'All available assets are already connected.'); return list; }
            pushToast(t.metaSyncedToast || 'Meta assets synced ✓');
            return [...list, { ...next, id: 'mc' + Date.now() }];
          });
        }
      } else if (p.mode === 'reauth') {
        setChannels((list) => list.map((c) => (c.id === p.rowId ? { ...c, status: 'active' } : c)));
        pushToast(t.metaReauthToast || 'Connection re-authorized ✓');
      } else if (p.mode === 'remove') {
        setChannels((list) => list.filter((c) => c.id !== p.rowId));
        pushToast(t.metaRemovedToast || 'Connection removed');
      } else {
        pushToast(t.metaManageToast || 'Permissions updated ✓');
      }
    }, 1300);
  };


  return (
    <div className="templates-page meta-service-page no-tree">
      <div className="content-panel">
        {/* Tabs on top — "Accounts" landing tab, same structure as Voice Service / Org Hierarchy. */}
        <div className="tabs-bar tabs-bar-with-toggle meta-tabs">
          <div className="tabs-bar-left">
            <button type="button" className="tab active">{t.metaTabAccounts || 'Accounts'}</button>
          </div>
        </div>

        <div className="content-body">
          <div className="node-header">
            <div className="node-title">
              {window.CgScopeLogo ? <window.CgScopeLogo node={scopeNode} size={32} /> : <BrandLogo brand={scopeNode?.brand} size={32} />}
              <span>{scopeNode ? scopeNode.name : (t.smVoice || 'Meta Service')}</span>
            </div>
            <div className="node-actions">
              {phase === 'hub' && (
                <button className="btn btn-primary" onClick={openAdd}><IcPlus size={15} stroke={2} /> {t.metaAddAccount || 'Add New Meta Account'}</button>
              )}
            </div>
          </div>

          {phase === 'purchase' && <MetaPurchaseGate offer={offer} t={t} onPurchase={purchase} />}
          {phase === 'activate' && <MetaActivateGate offer={offer} t={t} onActivate={activate} />}
          {phase === 'hub' && (
            <>
              <MetaChannelsGrid rows={channels} t={t} onManage={openManage} onReauth={openReauth} onRemove={openRemove} onDisable={doDisable} onEnable={doEnable} openMenuId={openMenuId} setOpenMenuId={setOpenMenuId} />
              <div className="meta-grid-note">{t.metaManageNote || 'Clicking "Manage" or "Re-auth" will securely redirect you back to Meta to update your permissions for that asset.'}</div>
            </>
          )}
        </div>
      </div>

      {popup && <MetaOAuthPopup mode={popup.mode} t={t} onClose={() => setPopup(null)} onAllow={onAllow} />}
      {syncing && <MetaSyncingOverlay t={t} />}
    </div>
  );
};

window.MetaServicePage = MetaServicePage;
