/* Ligações — setup de Apps / APIs / contas por marca.
   Expõe window.MktLigacoesScreen. */

async function mktLigFetch(url, opts) {
  const p = new URLSearchParams(window.location.search || '');
  const email = window.currentUser?.email || '';
  if (email && !p.get('email')) p.set('email', email);
  const full = url + (url.includes('?') ? '&' : '?') + p.toString();
  let res;
  try {
    res = await fetch(full, { headers: { 'Content-Type': 'application/json' }, ...opts });
  } catch (e) {
    throw new Error(`Erro de rede: ${e.message}`);
  }
  const body = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(body.error || `HTTP ${res.status}`);
  return body;
}

function mktLigStatus(status) {
  if (status === 'ligado') return { label: 'Ligado', color: '#166534', bg: 'rgba(22,163,74,.12)' };
  if (status === 'app_guardada') return { label: 'App guardada', color: '#92400E', bg: 'rgba(245,158,11,.14)' };
  if (status === 'em_breve') return { label: 'Em breve', color: 'var(--text-dim)', bg: 'var(--bg-sunken)' };
  return { label: 'Por ligar', color: '#92400E', bg: 'rgba(185,28,28,.08)' };
}

const MktLigLinkedInForm = ({ marcaSlug, lig, redirectUri, onSaved }) => {
  const [vanity, setVanity] = React.useState(lig?.vanity || 'biond-films');
  const [org, setOrg] = React.useState(String(lig?.organization_urn || '').replace(/^urn:li:organization:/, ''));
  const [clientId, setClientId] = React.useState('');
  const [clientSecret, setClientSecret] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState(null);
  React.useEffect(() => {
    setVanity(lig?.vanity || 'biond-films');
    setOrg(String(lig?.organization_urn || '').replace(/^urn:li:organization:/, ''));
  }, [lig?.vanity, lig?.organization_urn, marcaSlug]);
  React.useEffect(() => {
    const q = new URLSearchParams(window.location.hash.replace(/^#/, ''));
    if (q.get('li') === 'ok') setMsg('LinkedIn autorizado. Podes publicar na Activação.');
    if (q.get('li') === 'erro') setMsg(q.get('err') || 'OAuth LinkedIn falhou.');
  }, []);

  const inp = {
    fontSize: 12, fontFamily: 'inherit', color: 'var(--text)',
    border: '1px solid var(--border)', borderRadius: 6, padding: '7px 9px',
    background: 'var(--bg)', width: '100%',
  };

  const guardarApp = async () => {
    if (!clientId.trim() || !clientSecret.trim()) { setMsg('Client ID e Client Secret da App Community.'); return; }
    setBusy(true); setMsg(null);
    try {
      await mktLigFetch('/api/marketing/activacao/setup/linkedin-app', {
        method: 'POST',
        body: JSON.stringify({
          marca_slug: marcaSlug,
          client_id: clientId.trim(),
          client_secret: clientSecret.trim(),
        }),
      });
      setClientSecret('');
      setMsg('App guardada. Quando a Community Management estiver aprovada, clica Autorizar.');
      if (onSaved) await onSaved();
    } catch (e) { setMsg(e.message); }
    finally { setBusy(false); }
  };

  const autorizar = async () => {
    setBusy(true); setMsg(null);
    try {
      const qs = new URLSearchParams({
        marca_slug: marcaSlug,
        vanity: vanity.trim() || 'biond-films',
        organization_urn: org.trim() || '',
        return_to: 'ligacoes',
      });
      const out = await mktLigFetch(`/api/marketing/activacao/linkedin/auth-url?${qs.toString()}`);
      window.location.href = out.url;
    } catch (e) {
      setMsg(e.message);
      setBusy(false);
    }
  };

  return (
    <div style={{ display: 'grid', gap: 10, marginTop: 12 }}>
      <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.45 }}>
        Usa a App <b>Biond Community</b> (só Community Management API). Redirect URL na tab Auth:
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text)', marginTop: 4, wordBreak: 'break-all' }}>
          {redirectUri}
        </div>
      </div>
      <div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 3 }}>Vanity da company page</div>
        <input value={vanity} onChange={e => setVanity(e.target.value)} placeholder="biond-films" disabled={busy} style={inp} />
      </div>
      <div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 3 }}>Organization ID (opcional)</div>
        <input value={org} onChange={e => setOrg(e.target.value)} placeholder="só se o vanity falhar" disabled={busy} style={inp} />
      </div>
      <div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 3 }}>Client ID</div>
        <input value={clientId} onChange={e => setClientId(e.target.value)} placeholder="tab Auth da App Biond Community" disabled={busy} style={inp} autoComplete="off" />
      </div>
      <div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 3 }}>Client Secret</div>
        <input type="password" value={clientSecret} onChange={e => setClientSecret(e.target.value)} placeholder={lig?.has_app ? 'Já guardado — cola só para substituir' : 'tab Auth da App Biond Community'} disabled={busy} style={inp} autoComplete="off" />
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <button
          className="btn"
          disabled={!clientId.trim() || !clientSecret.trim() || busy}
          onClick={guardarApp}
          style={{ height: 32, padding: '0 14px', fontSize: 12, opacity: clientId.trim() && clientSecret.trim() && !busy ? 1 : 0.45 }}
        >
          {busy ? 'A guardar…' : '1. Guardar App'}
        </button>
        <button
          className="btn btn-ai"
          disabled={busy}
          onClick={autorizar}
          style={{ height: 32, padding: '0 14px', fontSize: 12 }}
        >
          {busy ? 'A autorizar…' : '2. Autorizar no LinkedIn'}
        </button>
      </div>
      <div style={{ fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.45 }}>
        Autorizar só funciona depois da Community Management sair de <b>Review in progress</b>.
        Usa a conta Admin da page. Não peças outros products nesta App.
      </div>
      {msg && (
        <div style={{ fontSize: 12, color: /autorizado|guardad/i.test(msg) ? '#166534' : '#92400E' }}>{msg}</div>
      )}
    </div>
  );
};

const MktLigacoesScreen = () => {
  const hashMarca = (() => {
    try { return new URLSearchParams(window.location.hash.replace(/^#/, '')).get('marca') || ''; }
    catch { return ''; }
  })();
  const [marca, setMarca] = React.useState(hashMarca || 'biond');
  const [data, setData] = React.useState(null);
  const [err, setErr] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  const load = React.useCallback(async (slug) => {
    setLoading(true); setErr(null);
    try {
      const out = await mktLigFetch(`/api/marketing/ligacoes?marca_slug=${encodeURIComponent(slug || marca)}`);
      setData(out);
      if (out.selected?.marca?.slug) setMarca(out.selected.marca.slug);
    } catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  }, [marca]);

  React.useEffect(() => { load(marca); }, []);

  const selected = data?.selected;
  const ligacoes = selected?.ligacoes || [];

  return (
    <div className="scrollbar" style={{ height: '100%', overflowY: 'auto', padding: '20px 24px 80px' }}>
      <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
        MARKETING · LIGAÇÕES
      </div>
      <h2 className="font-display" style={{ margin: '6px 0 6px', fontSize: 28, fontWeight: 500, letterSpacing: '-0.01em' }}>
        Apps, APIs e contas
      </h2>
      <div style={{ fontSize: 13, color: 'var(--text-muted)', maxWidth: 720, marginBottom: 18, lineHeight: 1.45 }}>
        Configuração por marca — não por campanha. A Activação só usa o que estiver ligado aqui.
      </div>

      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 18 }}>
        {(data?.marcas || []).map(m => (
          <button
            key={m.slug}
            type="button"
            className="btn"
            onClick={() => { setMarca(m.slug); load(m.slug); }}
            style={{
              height: 28, padding: '0 12px', fontSize: 12,
              borderColor: marca === m.slug ? (m.color || '#3859D0') : undefined,
              background: marca === m.slug ? 'rgba(56,89,208,0.08)' : undefined,
              fontWeight: marca === m.slug ? 700 : 500,
            }}
          >
            {m.name || m.slug}
          </button>
        ))}
      </div>

      {loading && <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>A carregar ligações…</div>}
      {err && <div style={{ fontSize: 13, color: '#b91c1c' }}>{err}</div>}

      <div style={{ display: 'grid', gap: 12, maxWidth: 820 }}>
        {ligacoes.map(lig => {
          const st = mktLigStatus(lig.status);
          return (
            <div key={lig.id} className="card" style={{ padding: 16 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                    <div className="font-display" style={{ fontSize: 16, fontWeight: 600 }}>{lig.label}</div>
                    <span style={{
                      fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.04em',
                      textTransform: 'uppercase', padding: '2px 7px', borderRadius: 4,
                      background: st.bg, color: st.color, fontWeight: 700,
                    }}>{st.label}</span>
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>{lig.desc}</div>
                  {lig.detail && (
                    <div style={{ fontSize: 11, color: 'var(--text)', marginTop: 6, fontFamily: 'var(--font-mono)', wordBreak: 'break-all' }}>
                      {lig.detail}
                    </div>
                  )}
                </div>
              </div>
              {lig.id === 'linkedin' && (
                <MktLigLinkedInForm
                  marcaSlug={selected?.marca?.slug || marca}
                  lig={lig}
                  redirectUri={data?.redirect_uri}
                  onSaved={() => load(selected?.marca?.slug || marca)}
                />
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

window.MktLigacoesScreen = MktLigacoesScreen;
