// LinkedClean — Popup v2 (revisado pós-UX review)
// DNA: paleta EarlyBird (off-white / ink / blue-as-accent), Geist, ícone M1.
// Mudanças desta rodada:
//   1. Toggles de categoria → preto (azul só no logo)
//   2. Header: switch grande virou pill "Ativo/Pausado"
//   3. Tirado o "5/5" inútil do header de categorias
//   4. Stats: hierarquia — Hoje protagonista, Semana subordinada
//   5. Label "Quando varrer" → "NO LUGAR DO POST"

const POPUP_V2_W = 380;

// =============================================================================
// STATUS PILL — controle global "Ativo / Pausado" (substitui o switch grande)
// Comunica MELHOR que é controle de nível diferente das categorias.
// =============================================================================
function StatusPill({ on, onClick }) {
  const { LC } = window;
  return (
    <button
      onClick={onClick}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '5px 10px 5px 8px',
        borderRadius: 999,
        background: on ? LC.ink : '#FFFFFF',
        color: on ? '#FFFFFF' : LC.ink50,
        border: on ? `1px solid ${LC.ink}` : `1px solid ${LC.ink15}`,
        fontFamily: 'inherit',
        fontSize: 11.5, fontWeight: 600,
        letterSpacing: '-0.005em',
        cursor: 'pointer',
        transition: 'all 0.18s ease',
      }}
      aria-label={on ? 'Pausar LinkedClean' : 'Ativar LinkedClean'}
    >
      <span style={{
        width: 6, height: 6, borderRadius: '50%',
        background: on ? '#7BD389' : LC.ink30,
        boxShadow: on ? '0 0 0 2px rgba(123,211,137,0.25)' : 'none',
      }} />
      {on ? 'Ativo' : 'Pausado'}
    </button>
  );
}

// =============================================================================
// CATEGORY ROW DENSO — 1 linha, ~40px
// =============================================================================
function CategoryRowDense({ Icon, name, count, on, onToggle, accentBlue }) {
  const { LC } = window;
  return (
    <div
      onClick={onToggle}
      style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '8px 0',
        cursor: 'pointer',
        userSelect: 'none',
      }}
    >
      <div style={{ width: 24, height: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        {Icon ? <Icon size={22} active={on} /> : null}
      </div>
      <div style={{
        flex: 1, minWidth: 0,
        fontSize: 13.5, fontWeight: 500,
        color: on ? LC.ink : LC.ink50,
        letterSpacing: '-0.005em',
      }}>
        {name}
      </div>
      {count != null && (
        <div style={{
          fontSize: 11, fontWeight: 600,
          color: on ? LC.ink50 : LC.ink30,
          fontFamily: '"Geist Mono", monospace',
          letterSpacing: '0.02em',
          minWidth: 28, textAlign: 'right',
        }}>
          {count}
        </div>
      )}
      <CompactToggle on={on} accentBlue={accentBlue} />
    </div>
  );
}

// Mini toggle for category rows — sempre PRETO (azul é exclusivo do logo)
function CompactToggle({ on }) {
  const { LC } = window;
  const w = 28, h = 16, knob = 12, pad = 2;
  const onColor = LC.ink;
  return (
    <span style={{
      width: w, height: h, borderRadius: h / 2,
      background: on ? onColor : LC.ink15,
      position: 'relative', flexShrink: 0,
      transition: 'background 0.18s ease',
      display: 'inline-block',
    }}>
      <span style={{
        position: 'absolute',
        top: pad,
        left: on ? (w - knob - pad) : pad,
        width: knob, height: knob, borderRadius: '50%',
        background: '#FFFFFF',
        boxShadow: '0 1px 2px rgba(0,0,0,0.18)',
        transition: 'left 0.18s ease',
      }} />
    </span>
  );
}

// =============================================================================
// SEGMENTED CONTROL — modo de varredura
// =============================================================================
function ModeSegmented({ value, onChange }) {
  const { LC } = window;
  const opts = [
    { id: 'card',     label: 'Card discreto', sub: 'Mostra um marcador onde estava o post' },
    { id: 'invisible', label: 'Nada',         sub: 'O post some completamente do feed' },
  ];
  return (
    <div>
      <div style={{
        display: 'flex',
        background: LC.ink04,
        borderRadius: 10,
        padding: 3,
        gap: 2,
      }}>
        {opts.map(o => {
          const active = value === o.id;
          return (
            <button
              key={o.id}
              onClick={() => onChange(o.id)}
              style={{
                flex: 1,
                padding: '8px 10px',
                fontSize: 13, fontWeight: active ? 600 : 500,
                fontFamily: 'inherit',
                color: active ? LC.ink : LC.ink50,
                background: active ? '#FFFFFF' : 'transparent',
                border: 'none', borderRadius: 8,
                cursor: 'pointer',
                letterSpacing: '-0.005em',
                boxShadow: active ? '0 1px 2px rgba(0,0,0,0.06), 0 0 0 1px rgba(0,0,0,0.04)' : 'none',
                transition: 'all 0.15s ease',
              }}
            >
              {o.label}
            </button>
          );
        })}
      </div>
      <div style={{
        marginTop: 8, fontSize: 11.5, color: LC.ink50, lineHeight: 1.4,
      }}>
        {opts.find(o => o.id === value)?.sub}
      </div>
    </div>
  );
}

// =============================================================================
// SECTION LABEL — uppercase com counter
// =============================================================================
function SectionLabelV2({ children, right }) {
  const { LC } = window;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      fontSize: 10.5, fontWeight: 700,
      color: LC.ink50,
      textTransform: 'uppercase',
      letterSpacing: '0.12em',
      marginBottom: 10,
    }}>
      <span>{children}</span>
      {right && <span style={{ letterSpacing: '0.04em', color: LC.ink40, fontWeight: 600 }}>{right}</span>}
    </div>
  );
}

// =============================================================================
// HEADER OVERFLOW MENU — versão + idioma + opções
// =============================================================================
function OverflowMenu({ open, onClose }) {
  const { LC } = window;
  if (!open) return null;
  const items = [
    { label: 'Idioma · Português', shortcut: null },
    { label: 'Pausar tudo por hoje', shortcut: null },
    { label: 'Configurações avançadas', shortcut: '↗' },
    { label: 'Compartilhar faxina', shortcut: '↗' },
    { label: 'Ajuda & feedback', shortcut: '↗' },
  ];
  return (
    <>
      <div
        onClick={onClose}
        style={{ position: 'absolute', inset: 0, zIndex: 5 }}
      />
      <div style={{
        position: 'absolute', top: 48, right: 16, zIndex: 6,
        width: 220,
        background: '#FFFFFF',
        borderRadius: 10,
        boxShadow: '0 12px 32px -8px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.06)',
        padding: 5, fontFamily: 'inherit',
      }}>
        {items.map((it, i) => (
          <div key={i} style={{
            padding: '8px 10px',
            fontSize: 13, fontWeight: 500,
            color: LC.ink, letterSpacing: '-0.005em',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            borderRadius: 7, cursor: 'pointer',
          }}>
            <span>{it.label}</span>
            {it.shortcut && <span style={{ color: LC.ink40, fontSize: 11 }}>{it.shortcut}</span>}
          </div>
        ))}
        <div style={{
          marginTop: 4, paddingTop: 8, paddingBottom: 4,
          borderTop: `1px solid ${LC.ink04}`,
          textAlign: 'center',
          fontFamily: '"Geist Mono", monospace',
          fontSize: 9.5, color: LC.ink30, letterSpacing: '0.08em',
        }}>
          linkedclean.app · v1.0.0
        </div>
      </div>
    </>
  );
}

// =============================================================================
// POPUP V2 SHELL
// =============================================================================
function PopupV2Shell({ density = 'comfortable' }) {
  const { LC, LCIcon, LCWordmark } = window;
  const [globalOn, setGlobalOn] = React.useState(true);
  const [mode, setMode] = React.useState('card');
  const [menuOpen, setMenuOpen] = React.useState(false);

  const {
    IconPatrocinado, IconEmpresa, IconVideo, IconBait,
    IconPolitica,
  } = window;

  const [cats, setCats] = React.useState([
    { id: 'patrocinado', Icon: IconPatrocinado, name: 'Post patrocinado',    count: 12, on: true },
    { id: 'empresa',     Icon: IconEmpresa,     name: 'Página de empresa',   count: 23, on: true },
    { id: 'video',       Icon: IconVideo,       name: 'Vídeo',               count: 18, on: true },
    { id: 'bait',        Icon: IconBait,        name: 'Iscas de engajamento', count: 14, on: true },
    { id: 'politica',    Icon: IconPolitica,    name: 'Conteúdo político',   count: 9,  on: true },
  ]);

  const onCount = cats.filter(c => c.on).length;
  const totalToday = cats.filter(c => c.on).reduce((a, c) => a + c.count, 0);

  const toggleCat = (id) => setCats(cats.map(c => c.id === id ? { ...c, on: !c.on } : c));

  // density tweak — affects category row vertical padding + section padding
  const padCat = density === 'compact' ? '6px 0' : '9px 0';
  const padSection = density === 'compact' ? 16 : 20;

  return (
    <div className="lc-popup-shell" style={{
      width: POPUP_V2_W,
      background: '#FFFFFF',
      fontFamily: '"Geist", -apple-system, sans-serif',
      color: LC.ink,
      borderRadius: 12,
      overflow: 'hidden',
      position: 'relative',
      boxShadow: '0 24px 60px -20px rgba(0,0,0,0.18), 0 4px 12px -4px rgba(0,0,0,0.08), 0 0 0 1px rgba(0,0,0,0.04)',
    }}>
      {/* HEADER */}
      <div style={{
        padding: '14px 16px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: `1px solid ${LC.ink04}`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <LCIcon size={26} />
          <LCWordmark size={15} />
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <StatusPill on={globalOn} onClick={() => setGlobalOn(!globalOn)} />
          <button
            onClick={() => setMenuOpen(!menuOpen)}
            style={{
              width: 28, height: 28, padding: 0,
              background: 'transparent', border: 'none', cursor: 'pointer',
              borderRadius: 6,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: LC.ink50,
            }}
            aria-label="Mais opções"
          >
            <svg width="14" height="14" viewBox="0 0 14 14"><circle cx="3" cy="7" r="1.4" fill="currentColor"/><circle cx="7" cy="7" r="1.4" fill="currentColor"/><circle cx="11" cy="7" r="1.4" fill="currentColor"/></svg>
          </button>
        </div>
      </div>

      <OverflowMenu open={menuOpen} onClose={() => setMenuOpen(false)} />

      {/* STATS — Hoje protagonista, Semana subordinada (hierarquia clara) */}
      <div style={{
        padding: `16px ${padSection}px 14px`,
        borderBottom: `1px solid ${LC.ink04}`,
        opacity: globalOn ? 1 : 0.4,
        transition: 'opacity 0.18s',
      }}>
        <div style={{
          fontSize: 9.5, fontWeight: 700, color: LC.ink50,
          textTransform: 'uppercase', letterSpacing: '0.12em',
          marginBottom: 6,
        }}>Hoje</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{
            fontSize: 36, fontWeight: 700, color: LC.ink,
            letterSpacing: '-0.035em', lineHeight: 0.95,
          }}>{totalToday}</span>
          <span style={{ fontSize: 13.5, fontWeight: 500, color: LC.ink60, letterSpacing: '-0.005em' }}>
            posts ocultados
          </span>
        </div>
        <div style={{
          marginTop: 8, paddingTop: 8,
          borderTop: `1px dashed ${LC.ink08}`,
          display: 'flex', alignItems: 'baseline', gap: 6,
          fontSize: 12, color: LC.ink50, letterSpacing: '-0.005em',
        }}>
          <span>Nos últimos 7 dias</span>
          <span style={{
            fontFamily: '"Geist Mono", monospace',
            fontWeight: 600, color: LC.ink, letterSpacing: '-0.01em',
          }}>~8min</span>
          <span>economizados</span>
        </div>
      </div>

      {/* CATEGORIAS — sem o "5/5" inútil; só aparece label se houver alguma off */}
      <div style={{ padding: `${padSection - 4}px ${padSection}px 8px`, opacity: globalOn ? 1 : 0.4, transition: 'opacity 0.18s' }}>
        <SectionLabelV2 right={onCount < cats.length ? `${onCount} ativas` : null}>
          Categorias
        </SectionLabelV2>
        <div>
          {cats.map((c, i) => (
            <div key={c.id} style={{
              padding: padCat,
              borderTop: i > 0 ? `1px solid ${LC.ink04}` : 'none',
            }}>
              <div
                onClick={() => toggleCat(c.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  cursor: 'pointer', userSelect: 'none',
                }}
              >
                <div style={{ width: 22, height: 22, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  {c.Icon ? <c.Icon size={20} active={c.on} /> : null}
                </div>
                <div style={{
                  flex: 1, minWidth: 0,
                  fontSize: 13.5, fontWeight: 500,
                  color: c.on ? LC.ink : LC.ink50,
                  letterSpacing: '-0.005em',
                }}>
                  {c.name}
                </div>
                <CompactToggle on={c.on} />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* DIVIDER */}
      <div style={{ height: 8, background: LC.ink02, borderTop: `1px solid ${LC.ink04}`, borderBottom: `1px solid ${LC.ink04}` }} />

      {/* MODO — label honesto: descreve o QUE, não o QUANDO */}
      <div style={{ padding: `${padSection - 2}px ${padSection}px ${padSection}px`, opacity: globalOn ? 1 : 0.4, transition: 'opacity 0.18s' }}>
        <SectionLabelV2>No lugar do post</SectionLabelV2>
        <ModeSegmented value={mode} onChange={setMode} />
      </div>
    </div>
  );
}

window.PopupV2Shell = PopupV2Shell;
window.StatusPill = StatusPill;
window.CompactToggle = CompactToggle;
window.ModeSegmented = ModeSegmented;
