/* Marketing · Brand context + sticky pill switcher.
   - MktBrandProvider envolve o módulo Marketing (no wrapper).
   - useMktBrand() devolve { brand, setBrand, isAll, brandObj }.
   - Estado sincronizado com URL hash param ?marca= (sobre o hash actual #screen=marketing).
   - <MktBrandPills hideOnSubAgentes /> sticky abaixo do topbar.
*/

const MktBrandCtx = React.createContext(null);

const readHashMarca = () => {
  try {
    const h = window.location.hash || '';
    // hash pode ser #screen=marketing&marca=mimaki
    const params = new URLSearchParams(h.replace(/^#/, ''));
    return params.get('marca') || null;
  } catch { return null; }
};
const writeHashMarca = (id) => {
  try {
    const h = window.location.hash || '';
    const params = new URLSearchParams(h.replace(/^#/, ''));
    if (!id || id === 'todas') params.delete('marca');
    else params.set('marca', id);
    const next = '#' + params.toString();
    if (next !== h) {
      // actualizar hash sem disparar handlers do portal (que reagem a 'screen')
      const url = window.location.pathname + window.location.search + next;
      window.history.replaceState(null, '', url);
    }
  } catch {}
};

const MktBrandProvider = ({ children }) => {
  const [brand, setBrandState] = React.useState(() => readHashMarca() || 'todas');

  const setBrand = React.useCallback((id) => {
    setBrandState(id || 'todas');
    writeHashMarca(id);
  }, []);

  // Listen to back/forward (hashchange) → sync state
  React.useEffect(() => {
    const onHash = () => {
      const m = readHashMarca() || 'todas';
      setBrandState(prev => prev === m ? prev : m);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const brandObj = (window.MKT_BRANDS || []).find(b => b.id === brand) || (window.MKT_BRANDS || [])[0];
  const isAll = brand === 'todas';

  return (
    <MktBrandCtx.Provider value={{ brand, setBrand, isAll, brandObj }}>
      {children}
    </MktBrandCtx.Provider>
  );
};

const useMktBrand = () => {
  const ctx = React.useContext(MktBrandCtx);
  if (!ctx) throw new Error('useMktBrand fora de MktBrandProvider');
  return ctx;
};

// Multi-gradient para a pill "Todas"
const TODAS_GRADIENT = 'conic-gradient(from 0deg, #e60012 0deg 51deg, #00a86b 51deg 102deg, #f59e0b 102deg 154deg, #8b5cf6 154deg 205deg, #ec4899 205deg 256deg, #22d3ee 256deg 308deg, #64748b 308deg 360deg)';

const MktBrandPills = ({ rightExtra }) => {
  const { brand, setBrand } = useMktBrand();
  const brands = window.MKT_BRANDS || [];
  const numbers = window.MKT_BRAND_NUMBERS || {};

  const totalLeads = Object.values(numbers).reduce((a, b) => a + (b.leads || 0), 0);

  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 30,
      background: 'var(--bg)',
      borderBottom: '1px solid var(--border)',
      padding: '10px 24px',
      display: 'flex', alignItems: 'center', gap: 16,
      flexWrap: 'wrap',
    }}>
      <div style={{
        fontSize: 9.5, color: 'var(--text-dim)',
        fontFamily: 'var(--font-mono)', letterSpacing: '0.1em',
        flexShrink: 0,
      }}>MARCA</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', flex: 1, minWidth: 0 }}>
        {brands.map(b => {
          const isActive = b.id === brand;
          const n = b.id === 'todas' ? { leads: totalLeads } : (numbers[b.id] || { leads: 0 });
          const dotBg = b.id === 'todas' ? TODAS_GRADIENT : b.cor;
          return (
            <button
              key={b.id}
              onClick={() => setBrand(b.id)}
              title={b.descricao}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 7,
                padding: '6px 12px',
                borderRadius: 999,
                fontSize: 12.5,
                fontWeight: isActive ? 600 : 500,
                fontFamily: 'var(--font-display)',
                letterSpacing: '0.01em',
                background: isActive
                  ? (b.id === 'todas' ? 'var(--brand-900)' : `color-mix(in oklch, ${b.cor} 22%, var(--bg-elev))`)
                  : 'transparent',
                color: isActive
                  ? (b.id === 'todas' ? '#fff' : 'var(--text)')
                  : 'var(--text-muted)',
                border: isActive
                  ? `1px solid ${b.id === 'todas' ? 'var(--brand-900)' : `color-mix(in oklch, ${b.cor} 50%, transparent)`}`
                  : '1px solid transparent',
                boxShadow: isActive && b.id !== 'todas'
                  ? `0 0 0 3px color-mix(in oklch, ${b.cor} 12%, transparent)`
                  : 'none',
                transition: 'all 0.15s ease',
                cursor: 'pointer',
                position: 'relative',
              }}
              onMouseEnter={e => {
                if (!isActive) { e.currentTarget.style.background = 'var(--bg-hover)'; e.currentTarget.style.color = 'var(--text)'; }
              }}
              onMouseLeave={e => {
                if (!isActive) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-muted)'; }
              }}
            >
              <span style={{
                width: 8, height: 8, borderRadius: '50%',
                background: dotBg,
                flexShrink: 0,
                boxShadow: b.id === 'todas' ? 'none' : `0 0 0 1px color-mix(in oklch, ${b.cor} 30%, transparent)`,
              }} />
              {b.nome}
              {b.id === 'todas' && (
                <span style={{ fontSize: 10, opacity: 0.65, fontFamily: 'var(--font-mono)' }}>(7)</span>
              )}
              {isActive && b.id !== 'todas' && n.leads > 0 && (
                <span style={{
                  fontSize: 10, fontFamily: 'var(--font-mono)',
                  padding: '1px 6px', borderRadius: 4,
                  background: 'var(--bg-sunken)',
                  color: 'var(--text-muted)',
                  marginLeft: 2,
                }}>{n.leads} leads</span>
              )}
            </button>
          );
        })}
      </div>
      {rightExtra && <div style={{ flexShrink: 0 }}>{rightExtra}</div>}
    </div>
  );
};

window.MktBrandProvider = MktBrandProvider;
window.useMktBrand = useMktBrand;
window.MktBrandPills = MktBrandPills;
window.MKT_TODAS_GRADIENT = TODAS_GRADIENT;
